Error Handling for REST with Spring for newbie

Ngchiwa Ng
2 min readNov 22, 2018

--

Come on, I just want to customize my error return object, why so complicate?

there are many many tutorial to customize Spring error handling, but there is no good for newbie to find which answer is easy adopt. in some tutorial web site, you will find, over 4 method to customize api error format. how can we choose?

(snapshot from : https://www.baeldung.com/exception-handling-for-rest-with-spring)

In this article, we focus on how to customize your error output in api.

This article, suit for :

1.developing api service with Spring MVC
2. Spring MVC newbie

in this article, we focus on how to customize your error output in api.

  1. create a ApiResponseEntityExceptionHandler which extend ResponseEntityExceptionHandler

just like this, and we will use annotation

@ControllerAdvice // about the ApiResponseEntityExceptionHandler

@ExceptionHandler(Exception.class) //above handle exception function

@ControllerAdvice
public class ApiResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler({Exception.class}) //define which exception you will handle
public final ResponseEntity<Object> handleUserNotFoundException(Exception ex, WebRequest request) {
HashMap <String, String> returnObject = new HashMap<>();
returnObject.put("error", ex.getMessage());
return new ResponseEntity<>(returnObject, HttpStatus.BAD_REQUEST); //return ResponseEntity including of your customer error object and http status code
}

}

2. in your controller throw Exception:

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {

@RequestMapping("/hello-world-error")
public Object healthCheck() throws Exception {
throw new Exception("my error!"); //throw exception
}

}

3. test it !

Recap:

  1. create a ApiResponseEntityExceptionHandler extends ResponseEntityExceptionHandler, it define which exception you what to handle.

@ControllerAdvice // about the ApiResponseEntityExceptionHandler

@ExceptionHandler(Exception.class) //above handle exception function

2. let throw exception in your controller.

hope this article can help Spring newbie :)

more info you can find:

ref:

https://www.baeldung.com/exception-handling-for-rest-with-spring

--

--

Ngchiwa Ng
Ngchiwa Ng

Written by Ngchiwa Ng

Backend/iOS Engineer, rock the world

No responses yet