Tag Archives: Exceptions

Handle uncaught exceptions in a Spring-Boot REST API – Part VI

Many times, we have seen exception thrown on your web page and all the stack trace of the exception. A non-technical user will not be able to understand most of the time. Also stack trace is not the best option when we can show the same exception error in nice json format with the root cause. In this post, we will show how to handle unhandled exceptions from our previous Spring REST API we built here. This particular feature will show how to handle most HTTP 500 errors which happen because of server side issues. Any errors with request or client side, those are HTTP 400 errors and they have been handled in previous post Error Handling in Spring Boot Rest API.


What happens when there is a database connection issue OR columns in your REST API are different from specified in database tables? Your API will throw a 500 error and if you don’t have any mechanism, this will display error in an html format which will not give much information to user or developer to resolve the issue.


JAX-RS provides a way to handle uncaught exceptions. This can be done by my implementing an interface for ExtendedExceptionMapper. Basically this is a contract for a provider that takes java exceptions and maps them to a response object which can be transformed into a JSON. This can be implemented as below:

package com.betterjavacode.benefits.utilities;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.glassfish.jersey.spi.ExtendedExceptionMapper;

public class UncaughtExceptionMapper implements ExtendedExceptionMapper<Throwable> {

private static final Logger LOGGER = LogManager.getLogger(UncaughtExceptionMapper.class);

public Response toResponse(Throwable exception) {
LOGGER.info("Enter >> toResponse ");
LOGGER.debug("Exception Caught: " + exception.getMessage());
LOGGER.info("Exit << toResponse");
return Response.status(Status.BAD_REQUEST)

public boolean isMappable(Throwable arg0) {
return !(arg0 instanceof WebApplicationException);


Basically this implementation shows a class UncaughtExceptionMapper implementing an interface ExtendedExceptionMapper which provides a way to map all exceptions which are not of type WebApplicationException (Most HTTP 400 errors are WebApplicationExceptions). toResponse method will help to log all the exceptions and convert exceptions into a Response object.


In this post, we showed how to map all uncaught exceptions into json format response. The code for this post is available at github repository.


Error Handling and Logging in Spring Boot REST API – Part III

In previous posts, I wrote about how to create a spring boot REST API Part I and how to add swagger documentation for REST API Part II. In this post, we will add error handling and logging to our REST API. Error handling and Logging are two different ideas, so I will divide this post in two sections.

1. Logging

In most production applications, logging is critical and it is used for multiple purposes. Few of those uses are debugging the production issues or auditing for the application. Over the years, different logging libraries have evolved to use in java based applications. slf4j is the most popular framework as it provides a simple abstraction layer to any kind of logging framework.

In our tutorial for this application, we will be using log4j2 which is the most recent and advance logging library out there. It provides lot of useful features for performance, support for multiple APIs, advance filtering, automatic reloading of configurations etc. We will not cover any of these in this article, if you are interested to read about log4j2 libraries, read here.

Add log4j2 library in application –

To use log4j2, we will add the maven dependency to our project’s pom file. This should look like below


Add log4j2 configuration file

To enable logging, we will have to add a configuration file in our application. This configuration file can be XML, JSON or YAML file. We will be using a XML file log4j2.xml which will look like below

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
 <Console name="Console" target="SYSTEM_OUT">
 <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
 <File name="BenefitsFile" fileName="benefits.log" append="true">
 <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
 <Root level="debug">
 <AppenderRef ref="Console" />
 <AppenderRef ref="BenefitsFile"/>

So we are using <code> Console </code> and <code> BenefitsFile </code> as two loggers which will log into a console and file respectively. We are setting log level to DEBUG. If you log any messages with a level lower than DEBUG, they will be logged into console or file. We will have to add a file benefits.log in classpath to achieve this logging in file. Log pattern is with date time, log level, class from which log is originating and log message.

Add logging in application code

Once we have required logging libraries and logging configuration adjusted, we can add logging in our code to capture this logging during runtime execution. In one of the managers CompanyManagerImpl, we will add a logger.

public static final Logger LOGGER = LogManager.getLogger(CompanyManagerImpl.class);

public List<Company> getAllCompanies()
LOGGER.info(" Enter >> getAllCompanies() ");
List<Company> cList = (List<Company>) companyRepository.findAll();
LOGGER.info(" Exit << getAllCompanies() ");
return cList;

Now once we execute our spring boot application, we can capture the logs in console or file. The file will be benefits.log.

2. Error Handling

We will not write about exceptions in detail as it has been covered in this post Exceptions. We will create our own custom exception which will be extended from WebApplicationException which jersey library provides.

This will look like below:

package com.betterjavacode.benefits.utilities;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;

public class InvalidRequestException extends WebApplicationException {

private static final long serialVersionUID = 1L;
private int errorcode = 00; // 00 indicates - no error

public InvalidRequestException() {


public InvalidRequestException(int errorcode, String message) {
this.errorcode = errorcode;

public InvalidRequestException(int errorcode, String message, Throwable cause) {
super(cause, Response.status(Response.Status.BAD_REQUEST)
this.errorcode = errorcode;

Now we can use this custom exception in our managers when we want to throw an error message to indicate if there is anything wrong with client request. Similarly we can build another exception to show if there is anything wrong on server side. Following snippet shows from CompanyManagerImpl where we have shown how to throw this exception.

public Company getCompany(int guid) {
LOGGER.info(" Enter >> getCompany() ");
Company company = companyRepository.findOne(guid);
if (company == null) {
LOGGER.info(" Exit << createCompany() ");
throw new InvalidRequestException(400, "Company not found");
LOGGER.info(" Exit << getCompany() ");
return company;

In this post, we showed how to handle logging and errors in a REST API. The code for this is available on github repository.


Handling exceptions

During vulnerability scanning, we figured out there were lot of exceptions handled through print statement. That’s not very efficient way of handling exceptions. Print statements are still better than not writing anything to handle. That’s known as swallowing an exception. A good approach to handle exceptions is to write some way to log those exceptions or throw those exceptions with stack trace during runtime.

What are exceptions ?

Exceptions are error events. These events happen during runtime of a program. This generally disrupts the flow of the program.

There are three components to exception handlers – try, catch and finally.

try – This part of exception handling contains code which will be executed during every flow.

catch – If code in try part throws a runtime exception, that will be caught in catch part.

finally – This contains the code you want to execute after try part of execution is done. This ensures that finally block is executed even when unexpected exceptions occur. It is mostly used to clean up resources.

Types of Exceptions –

  • Unchecked Exceptions – Exception types that are direct or indirect subclasses of  class RuntimeException , those are unchecked exception.
  • Checked Exceptions – Exceptions that inherit Exception class are known as checked exceptions. RuntimeException are also extended from Exception , but client code doesn’t have to handle them, while Checked exceptions have to be handled by catch or throws clause.

How to handle Exceptions

  1. What exceptions to use? Checked or Unchecked?
    – In case the code doesn’t know what to do if an exception is thrown, it should be a unchecked exception. If code using an exception knows what to do to recover
    from that exception along with logging that information, that should be checked exception.
  2. Preserve encapsulation
    – Don’t propagate an exception from data access layer to business object layer.
    Example – SQLException is a RuntimeException. If data access layer throws this exception in following manner , catch block will not do anything, but will suppress it.

      public void dataAccessCode()
    catch (SQLException ex)

    On other hand to preserve encapsulation, the same runtime exception can be converted into another unchecked exception like below

    public void dataAccessCode()
    catch (SQLException ex)
    throw new RuntimeException(ex);

    Best practices for Exceptions
    1) Use finally block for cleaning the code
    2) Do not ignore or suppress an exception
    3) Log exceptions once
    4) Do not use exceptions for flow control


  1. Best Practices for Exceptions
  2. Exceptions by Oracle
  3. Checked Exceptions by Bruce Eckel