Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Handling Spring MVC Exceptions Using @ExceptionHandler Annotation

DZone's Guide to

Handling Spring MVC Exceptions Using @ExceptionHandler Annotation

This approach is ideal as it helps us reuse and centralize exception/error handling in Spring MVC/REST controllers.

· Integration Zone ·
Free Resource

The Future of Enterprise Integration: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation.

The Spring framework 3 provides an annotation @ExceptionHandler that can be used to intercept uncaught/unhandled exceptions in request mapped functions in controllers.


In the example below, we are throwing an Exception from a method that is called whenever /example is called. When spring determines that an uncaught exception is being thrown by the method, it calls the errorResponse method as it is annotated with @ExceptionHandler. The errorResponse method can then be used to construct a JSON response (which in this case is a result of serializing a Map containing error message and exception stacktrace).


This approach is ideal as it helps us reuse and centralize exception/error handling in Spring MVC/REST controllers.

@Controller
@RequestMapping(value="/example")
public class ExampleController {

@RequestMapping(value = "", method = RequestMethod.POST)
@ResponseBody
public void example() throws Exception{
System.out.println("in the example function");
throw new Exception("a new Exception");
}

@ExceptionHandler(Exception.class)
@ResponseBody
public Map<String,String> errorResponse(Exception ex, HttpServletResponse response){
Map<String,String> errorMap = new HashMap<String,String>();
errorMap.put("errorMessage",ex.getMessage());

StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
String stackTrace = sw.toString();

errorMap.put("errorStackTrace", stackTrace);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());

return errorMap;

}
}

Make your mark on the industry’s leading annual report. Fill out the State of API Integration 2019 Survey and receive $25 to the Cloud Elements store.

Topics:
java ,enterprise-integration ,spring mvc ,integration ,tips and tricks ,exception handling ,spring 3

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}