Controller Advice — Exception Handler in Spring Boot

What is @ControllerAdvice ?

Comparison with @ExceptionHandler

@RestController
@RequestMapping("/companies")
public class CompanyController
{

@GetMapping
public List<Company> getAllCompanies(HttpServletRequest req) throws Exception {

}
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
logger.error("Request: " + req.getRequestURL() + " raised " + ex);

ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}

}
@RestController
@RequestMapping("/users")
public class UserController
{

@GetMapping
public List<User> getAllUsers(HttpServletRequest req) throws Exception {

}
@ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
logger.error("Request: " + req.getRequestURL() + " raised " + ex);

ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}

}

Example of Controller Advice

  • Exception handling method annotated with @ExceptionHandler
  • Model enhancement methods annotated with @ModelAttribute
  • Binder initialization methods annotated with @InitBinder
@ControllerAdvice
public class GlobalExceptionHandler
{

@ExceptionHandler(CompanyNotFoundException.class)
public ModelAndView handleError(HttpServletRequest req, CompanyNotFoundException ex)
{
logger.error("Request: " + req.getRequestURL() + " raised " + ex);

ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}

@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity handleUserExceptionError(HttpServletRequest req, HttpServletResponse res, UserNotFoundException ex)
{
List errors = Collections.singletonList(ex.getMessage());
// Get headers
if(HttpStatus.INTERNAL_SERVER_ERROR.equals(res.getStatus()))
{
// do something
}

return new ResponseEntity<>(new ApiError(errors), headers, status);
}

}

Conclusion

--

--

--

Software Developer, Writer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Holy Grail of Multitenancy? Laravel and Jetstream w/ Teams

Best Practices for WordPress on AWS | AWS White Paper Summary

P vs. NP — The Biggest Unsolved Problem in Computer Science

Northsec CTF Writeup: Failing revenge

What is ELK Stack? How to deploy ELK using Docker, AWS EC2 and AWS Elastic Search

Using Browser Cookies and Voyager API to Scrape LinkedIn via Python with search

Data Mapping in Frontend Applications

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yogesh Mali

Yogesh Mali

Software Developer, Writer

More from Medium

How To Use Spring Boot Initialzer?

Spring @RestControllerAdvice When and Why?

Logging in Java

multi threading in java