Category Archives: Logging

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 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) {"Enter >> toResponse ");
LOGGER.debug("Exception Caught: " + exception.getMessage());"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()
{" Enter >> getAllCompanies() ");
List<Company> cList = (List<Company>) companyRepository.findAll();" 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;


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) {" Enter >> getCompany() ");
Company company = companyRepository.findOne(guid);
if (company == null) {" Exit << createCompany() ");
throw new InvalidRequestException(400, "Company not found");
}" 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.