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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Transform Any Type of Java Bean With BULL
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project

Trending

  • Issue and Present Verifiable Credentials With Spring Boot and Android
  • The 4 R’s of Pipeline Reliability: Designing Data Systems That Last
  • Java Virtual Threads and Scaling
  • Evolution of Cloud Services for MCP/A2A Protocols in AI Agents
  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.

By 
Jesus J. Puente user avatar
Jesus J. Puente
·
Nov. 30, 18 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
151.6K 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
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!