Spring boot - custom rest controller exception handling HTTP status

spring rest exception handling json
spring boot jpa exception handling
spring boot exception handling in service layer
spring boot bad request exception
exception handling in spring boot microservices
spring boot errorcontroller
spring security exception handling
spring boot exception handling mkyong

I have created a custom REST Controller Exception Handler for my spring boot application ...

@ControllerAdvice(annotations = RestController.class)
public class RestControllerExceptionHandler {    
  @ExceptionHandler(TechnicalException.class)
  public ResponseEntity handleTechnicalException(TechnicalException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getMessage()), BAD_REQUEST
    );
  }

  @ExceptionHandler(BusinessException.class)
  public ResponseEntity handleBusinessException(BusinessException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getMessage()), BAD_REQUEST
    );
  }

  @ExceptionHandler(ValidationException.class)
  public ResponseEntity handleValidationException(ValidationException e) {    
    return new ResponseEntity<>(
        new RestErrorMessageModel(e.getErrorCode(), e.getDetails()), BAD_REQUEST
    );
  }
}

... where I handle validation, business (exceptions that caused because of violation of business rules) and technical (database related, invalid request parameters, etc.) exceptions.

The exception classes have two parameters: errorCode (unique enum) and message (exception details).

As you can see from the example, for all cases I return BAD_REQUEST (400) status, which is not the best practice.

I would like to know the best way to handle HTTP statuses based on the exception category, for example: for validation errors returning BAD_REQUEST (400) status is "okay".

... or is there any way which lets spring-boot "decides" which status code to send?

Custom Error Message Handling for REST API, Implement a Global Exception Handler for a REST API with Spring. Learn Spring course, focused on the fundamentals of Spring 5 and Spring Boot 2: public ApiError(HttpStatus status, String message, List<String> errors) {. Please refer to the this great blog post for details: Exception Handling in Spring MVC NOTE In Spring MVC using @ResponseBody annotation is redundant - it's already included in @RestController annotation.

Since the type of errors may vary in application and it is not possible to have common HTTP status for all these errors I solved it by creating custom mapper which maps error codes to HTTP statuses.

Since error codes are unique and each of them used for a special exception handling, I can map error codes to Http statuses.

Guide to Spring Boot REST API Error Handling, Spring Boot gives very useful error messages to engineers building REST APIs. cover how to do proper error handling when building a REST API with Spring Boot. A common scenario is a http code 400 that means a BAD_REQUEST, when the client, To handle this case, we'll be creating a custom exception called� Handling Custom Exceptions. Now we’ll see how to create a method that handles an exception that is not yet declared inside Spring Boot’s ResponseEntityExceptionHandler. A common scenario for a Spring application that handles database calls is to have a call to find a record by its ID using a repository class.

You can always setup HttpStatus property in Exception and in Handler just get value of status and configure it in ResponseEntity. Basically HttpStatus depends on context of executed task. Your Technical or Business Exception can return 400, 404, 409 etc. I think good solution is define HttpStatus during throwing suitable exception. If you dont want to define many Exception per HttpStatus you can use org.springframework.web.server.ResponseStatusException.

Spring Boot Exception Handling for RESTful Services Errors , You will understand and implement HTTP Error Response statuses based on the How/What to think when you design error handling for REST API? Response uses the custom error structure that we had defined earlier. NOTE: Revised April 2018 Spring MVC provides several complimentary approaches to exception handling but, when teaching Spring MVC, I often find that my students are confused or not comfortable with them. Today I’m going to show you the various options available.

Spring REST Error Handling Example, In this article, we will show you error handling in Spring Boot REST application. how Spring Boot generates the default JSON error response. In Spring Boot, we can use @ControllerAdvice to handle custom exceptions. 2. Spring boot exception handling – REST request validation 2.1. Default spring validation support. To apply default validation, we only need to add relevant annotations in proper places. i.e. Annotate model class with required validation specific annotations such as @NotEmpty, @Email etc.

Custom Error Handling in REST Controllers with Spring Boot, This tutorial looks at REST API error handling in Spring Boot and where Even if we decide to handle all exceptions using a custom @ExceptionHandler Sometimes, just by using an appropriate HTTP status code, we can't� Spring Boot Tutorials. Hands-on examples. - Basics of Spring Boot. Covers Spring Boot Starter Projects, Spring Initializr, Creating REST Services, Unit and Integration tests, Profiles, Spring Boot Data JPA, Actuator and Security

REST API Error Handling With Spring Boot, Our goal is to not handle exceptions explicitly in Controller methods At start-up, Spring Boot tries to find a mapping for /error . curl -H "Accept: application/json" http://localhost:8080/no-such-page Impatient REST developers may choose to skip directly to the section on custom REST error responses. First, this guide covers the basic topics: how to capture an exception at controller level in Spring Boot and map it to a given HTTP status code. We’ll do that with the @ExceptionHandler and @ControllerAdvice annotations.

Comments
  • More or less the rule of thumb is this: 4xx = client error ==> tells the client of your web service that they have made something wrong. 5xx = server error ==> tells the client that you (the web service server) have some issues. 4xx = you forgot to give me flowers, 5xx = I have a headache :)
  • What do you mean by custom mapper?
  • @HarryCoder the custom method which returns HttpStatus based on errorCode: if (errorCode in (....)) then return HttpStatus.NOT_FOUND else if (errorCode in (....)) then return HttpStatus.CONFLICT etc.
  • It would be great of you could add a code snippet in addition to your explanation.