DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How to Transform Any Type of Java Bean With BULL
  • Implementing a Method Trace Infrastructure With Spring Boot and AspectJ
  • Spring Boot Annotations: Behind the Scenes and the Self-Invocation Problem
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl

Trending

  • Extracting Maximum Value From Logs
  • A Complete Guide to Open-Source LLMs
  • Understanding Europe's Cyber Resilience Act and What It Means for You
  • Development of Custom Web Applications Within SAP Business Technology Platform
  1. DZone
  2. Coding
  3. Frameworks
  4. Customize HTTP Error Responses in Spring Boot

Customize HTTP Error Responses in Spring Boot

Learn more about customizing error responses in Spring Boot.

Jesus J. Puente user avatar by
Jesus J. Puente
·
Nov. 30, 18 · Tutorial
Like (18)
Save
Tweet
Share
149.54K Views

Join the DZone community and get the full member experience.

Join For Free

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

Spring Framework Spring Boot Object (computer science)

Opinions expressed by DZone contributors are their own.

Related

  • How to Transform Any Type of Java Bean With BULL
  • Implementing a Method Trace Infrastructure With Spring Boot and AspectJ
  • Spring Boot Annotations: Behind the Scenes and the Self-Invocation Problem
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: