Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Customize HTTP Error Responses in Spring Boot

DZone's Guide to

Customize HTTP Error Responses in Spring Boot

Learn more about customizing error responses in Spring Boot.

· Java Zone ·
Free Resource

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

In this article, I will explain how to return custom HTTP errors in Spring Boot. When we make an HTTP request to a resource, it is common that the request has to consider the option of returning an error.

It is the typical case that we made a RESTful request to query for a record, but it does not exist. In this case, you will usually return an HTTP code 404 (Not Found), and with this code, you also return a JSON object that with a a format defined for Spring Boot, like this:

{
    "timestamp": "2018-11-20T11:46:10.255+0000",
    "status": 404,
    "error": "Not Found",
    "message": "bean: 8 not Found",
    "path": "/get/8"
}


But if we want the output to be something like this:

{
    "timestamp": "2018-11-20T12:51:42.699+0000",
    "mensaje": "bean: 8 not Found",
    "detalles": "uri=/get/8",
    "httpCodeMessage": "Not Found"
}


We have to put a series of classes to our project. Here, I explain how.

I have the source code in my repository on GitHub.

Starting from a basic project Spring Boot, where we have a simple object called MiBean with only two fields:  code and value.This object will be returned in the requests to the resource /get so that a request to: http://localhost: 8080/get /1 return a JSON object like this:

{
    "codigo": 1,
    "valor": "valor uno"
}


If you try to access a higher element three, it will return an error because only three records are available.

This is the class ErrorResource that process the requests to the resource /get.

public class ErrorResource {

  @Autowired
  MiBeanService service;

  @GetMapping("/get/{id}")
  public MiBean getBean(@PathVariable int id) {
    MiBean bean = null;
    try 
    {
       bean = service.getBean(id);
    } catch (NoSuchElementException k)
    {
      throw new BeanNotFoundException("bean: "+id+ " not Found" );
    }
    return bean;
  }
}


As seen in thegetBean() function, we call to function getBean(int id) of the  MiBeanServiceobject. This is the source of that object.

@Component
public class MiBeanService {
  private static  List<MiBean> miBeans = new ArrayList<>();

  static {
    miBeans.add(new MiBean(1, "valor uno"));
    miBeans.add(new MiBean(2, "valor dos"));
    miBeans.add(new MiBean(3, "valor tres"));
  }

  public MiBean getBean(int id) {
    MiBean miBean =
        miBeans.stream()
         .filter(t -> t.getCodigo()==id)
         .findFirst()
         .get();

    return miBean;
  }

}


The function getBean(int id) throws an exception of the type NoSuchElementException if it doesn't find the value at List miBeans. This exception will be captured in the controller and it throws a exception of typeBeanNotFoundException.

ClassBeanNotFoundExceptionis as follows:

@ResponseStatus(HttpStatus.NOT_FOUND)
public class BeanNotFoundException  extends RuntimeException {
  public BeanNotFoundException(String message) {
    super(message);
  }
}


A simple class that extendsRuntimeException, and this annotated with the tag @ResponseStatus(HttpStatus.NOT_FOUND) will return a 404 code to the client.

Now if we make a request for a code greater than three, we will receive this response:

Image title

But, as we said, we want the error message is customized.

To do this, we will create a new class where our fields define the error message. This class is  ExceptionResponse, which is a simple POJO as you can see in the code attached:

public class ExceptionResponse {
  private Date timestamp;
  private String mensaje;
  private String detalles;
  private String httpCodeMessage;

  public ExceptionResponse(Date timestamp, String message, String details,String httpCodeMessage) {
    super();
    this.timestamp = timestamp;
    this.mensaje = message;
    this.detalles = details;
    this.httpCodeMessage=httpCodeMessage;
  }

  public String getHttpCodeMessage() {
    return httpCodeMessage;
  }

  public Date getTimestamp() {
    return timestamp;
  }

  public String getMensaje() {
    return mensaje;
  }

  public String getDetalles() {
    return detalles;
  }

}


This is the class to indicate which is the JSON object that it should return if an exception of type BeanNotFoundExceptionis thrown.

And now, we write the code to configure Spring for throw this JSON object.

This is the write-in: CustomizedResponseEntityExceptionHandler, which is attached below:

@ControllerAdvice
@RestController
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(BeanNotFoundException.class)
  public final ResponseEntity<ExceptionResponse> handleNotFoundException(BeanNotFoundException ex, WebRequest request) {
    ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
        request.getDescription(false),HttpStatus.NOT_ACCEPTABLE.getReasonPhrase());
    return new ResponseEntity<ExceptionResponse>(exceptionResponse, HttpStatus.NOT_ACCEPTABLE);
  }

}


This class must extend the  ResponseEntityExceptionHandler, which handles the most common exceptions.

We annotate it with the labels @ControllerAdvice and @RestController.

@ControllerAdvice is derived from @Component and will be used for classes that deal with exceptions. And as the class has the @RestContoller label, it handles only exceptions thrown in REST controllers.

In the handleNotFoundException function, we have defined that when BeanNotFoundException exception is thrown, it must return a ExceptionResponse object. This is done by creating an object ResponseEntity conveniently initiated.

It is important to note that it defines the HTTP code returned. In this case, we return the code 406 instead of the 404. In fact, in our example, we could remove the label @ResponseStatus(HttpStatus.NOT_FOUND)to the class BeanNotFoundException and everything would work the same.

And so, we have a custom output, as shown in the following image:

Image title

How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.

Topics:
java ,spring boot ,errror response ,http ,tutorial ,customize

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}