DEV Community

Cover image for @RestControllerAdvice Example SpringBoot
loizenai
loizenai

Posted on

@RestControllerAdvice Example SpringBoot

https://loizenai.com/restcontrolleradvice-springboot-example/

Tutorial: “@RestControllerAdvice Example SpringBoot – Error Handling for REST with Spring”.

In the article, I introduce about @RestControllerAdvice annotation of SpringBoot to handle RestAPI exception with a Github running sourcecode and details explanation example steps.

Read more: https://loizenai.com/angular-10-spring-boot-jwt-authentication-example/

https://dev.to/ozenero/angular-11-springboot-jwt-authentication-example-spring-security-mysql-20b8

  • Technologies we use in the article: – Java 1.8 – Maven

Annotation Type @RestControllerAdvice

@RestControllerAdvice is a new feature of Spring Framework 4.3, an annotation with combined @ControllerAdvice + @ResponseBody. So @RestControllerAdvice can help us to handle Exception with RestfulApi by a cross-cutting concern solution: @ExceptionHandler.

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @ControllerAdvice
 @ResponseBody
public @interface RestControllerAdvice
Enter fullscreen mode Exit fullscreen mode

@RestControllerAdvice is processed if an appropriate HandlerMapping-HandlerAdapter pair is configured such as the RequestMappingHandlerMapping-RequestMappingHandlerAdapter pair which are the default in the MVC Java config and the MVC namespace.

@RestControllerAdvice
public class WebRestControllerAdvice {

  @ExceptionHandler(CustomNotFoundException.class)
  public ResponseMsg handleNotFoundException(CustomNotFoundException ex) {
    ResponseMsg responseMsg = new ResponseMsg(ex.getMessage());
    return responseMsg;
  }
}
Enter fullscreen mode Exit fullscreen mode

The handleNotFoundException method will handle all exceptions has type: CustomNotFoundException from any @RequestMapping like:

@RequestMapping(value="/customer/{name}")
public Customer findCustomerByName(@PathVariable("name")String name){

  Customer cust = customerService.findCustomerByName(name);

  if(null == cust){
    throw new CustomNotFoundException("Not found customer with name is " + name);
  }

  return cust;
}
Enter fullscreen mode Exit fullscreen mode

Related post

Youtube video

Top comments (0)