Over a million developers have joined DZone.

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

Share, secure, distribute, control, and monetize your APIs with the platform built with performance, time-to-value, and growth in mind. Free 90-day trial of 3Scale by Red Hat

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.

public class ExampleController {

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

public Map<String,String> errorResponse(Exception ex, HttpServletResponse response){
Map<String,String> errorMap = new HashMap<String,String>();

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

errorMap.put("errorStackTrace", stackTrace);

return errorMap;


Explore the core elements of owning an API strategy and best practices for effective API programs. Download the API Owner's Manual, brought to you by 3Scale by Red Hat

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

Published at DZone with permission of Faheem Sohail, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}