Spring @ExceptionHandler does not work with @ResponseBody
Asked Answered
F

7

27

I try to configure a spring exception handler for a rest controller that is able to render a map to both xml and json based on the incoming accept header. It throws a 500 servlet exception right now.

This works, it picks up the home.jsp:

@ExceptionHandler(IllegalArgumentException.class)
public String handleException(final Exception e, final HttpServletRequest request, Writer writer)
{
    return "home";
}

This does not work:

@ExceptionHandler(IllegalArgumentException.class)
public @ResponseBody Map<String, Object> handleException(final Exception e, final HttpServletRequest request, Writer writer)
{
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put("errorCode", 1234);
    map.put("errorMessage", "Some error message");
    return map;
}

In the same controller mapping the response to xml or json via the respective converter works:

@RequestMapping(method = RequestMethod.GET, value = "/book/{id}", headers = "Accept=application/json,application/xml")
public @ResponseBody
Book getBook(@PathVariable final String id)
{
    logger.warn("id=" + id);
    return new Book("12345", new Date(), "Sven Haiges");
}
Fatuitous answered 23/2, 2011 at 21:8 Comment(1)
possible duplicate of ExceptionHandler returning JSON or XML not working in spring mvc 3Cursory
A
23

Your method

@ExceptionHandler(IllegalArgumentException.class)
public @ResponseBody Map<String, Object> handleException(final Exception e, final HttpServletRequest request, Writer writer)

does not work because it has the wrong return type. @ExceptionHandler methods have only two valid return types:

  • String
  • ModelAndView.

See http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html for more information. Here's the specific text from the link:

The return type can be a String, which is interpreted as a view name or a ModelAndView object.

In response to the comment

Thanx, seems I overread this. That's bad... any ideas how to provides exceptions automatically in xml/json format? – Sven Haiges 7 hours ago

Here's what I've done (I've actually done it in Scala so I'm not sure if the syntax is exactly correct, but you should get the gist).

@ExceptionHandler(Throwable.class)
@ResponseBody
public void handleException(final Exception e, final HttpServletRequest request,
        Writer writer)
{
    writer.write(String.format(
            "{\"error\":{\"java.class\":\"%s\", \"message\":\"%s\"}}",
            e.getClass(), e.getMessage()));
}
Alcatraz answered 23/2, 2011 at 21:46 Comment(4)
Thanx, seems I overread this. That's bad... any ideas how to provides exceptions automatically in xml/json format?Fatuitous
Hi there, just to comment that the return type for @ExceptionHandler methods are very wide. According to the documentation, it can be a ModelAndView,a Model object, a java.util.Map, a org.springframework.web.servlet.View, a String or voidDkl
Note that since you have no return type (void) that @ResponseBody has no meaning and can be omitted.Levite
Yes, since Spring 3.1, @ResponseBody methods can return an object, this will be passed to a HttpMessageConverter to be transformed into a representation.Aemia
A
13

Thanx, seems I overread this. That's bad... any ideas how to provides exceptions automatically in xml/json format?

New in Spring 3.0 MappingJacksonJsonView can be utilized to achieve that:

private MappingJacksonJsonView  jsonView = new MappingJacksonJsonView();

@ExceptionHandler(Exception.class)
public ModelAndView handleAnyException( Exception ex )
{
    return new ModelAndView( jsonView, "error", new ErrorMessage( ex ) );
}
Abet answered 8/11, 2011 at 8:33 Comment(2)
Since Spring 4.0.0 MappingJacksonJsonView has its constructor deprecated. See: docs.spring.io/spring/docs/4.0.5.RELEASE/javadoc-api/org/…Romeu
@Romeu Not because it is an invalid approach though, just because they are pushing migration to MappingJackson2JsonViewOutwardly
N
10

This seems ilke a confirmed Bug (SPR-6902 @ResponseBody does not work with @ExceptionHandler)

https://jira.springsource.org/browse/SPR-6902

Fixed in 3.1 M1 though...

Nursemaid answered 6/5, 2011 at 5:44 Comment(0)
I
8

I am using Spring 3.2.4. My solution to the problem was to make sure that the object I was returning from the exception handler had getters.

Without getters Jackson was unable to serialize the object to JSON.

In my code, for the following ExceptionHandler:

@ExceptionHandler(RuntimeException.class)
@ResponseBody
public List<ErrorInfo> exceptionHandler(Exception exception){
    return ((ConversionException) exception).getErrorInfos();
}

I needed to make sure my ErrorInfo object had getters:

package com.pelletier.valuelist.exception;

public class ErrorInfo {
private int code;
private String field;
private RuntimeException exception;

public ErrorInfo(){}

public ErrorInfo(int code, String field, RuntimeException exception){
    this.code = code;
    this.field = field;
    this.exception = exception;
}

public int getCode() {
    return code;
}

public String getField() {
    return field;
}

public String getException() {
    return exception.getMessage();
}
}
Ingressive answered 16/6, 2016 at 22:56 Comment(1)
Thanks! Was facing similar issue, adding getters solved the problemSalpinx
E
6

The following could be a workaround if you are using message converters to marshall error objects as the response content

@ExceptionHandler(IllegalArgumentException.class)
public String handleException(final Exception e, final HttpServletRequest request)
{
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put("errorCode", 1234);
    map.put("errorMessage", "Some error message");
    request.setAttribute("error", map);
    return "forward:/book/errors"; //forward to url for generic errors
}

//set the response status and return the error object to be marshalled
@SuppressWarnings("unchecked")
@RequestMapping(value = {"/book/errors"}, method = {RequestMethod.POST, RequestMethod.GET})
public @ResponseBody Map<String, Object> showError(HttpServletRequest request, HttpServletResponse response){

    Map<String, Object> map = new HashMap<String, Object>();
    if(request.getAttribute("error") != null)
        map = (Map<String, Object>) request.getAttribute("error");

    response.setStatus(Integer.parseInt(map.get("errorCode").toString()));

    return map;
}
Exurbia answered 15/8, 2011 at 9:54 Comment(1)
This should definitely be chosen as the answer for this topic! Thank you, dude!Underhanded
T
3

AnnotationMethodHandlerExceptionResolver also need MappingJacksonHttpMessageConverter

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver">
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>

<bean id="jacksonObjectMapper"
    class="iacm.cemetery.framework.web.servlet.rest.JacksonObjectMapper" />
Traditor answered 21/3, 2013 at 6:42 Comment(1)
i didn't realize org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter's messageConverters needed to be copied over to org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver. The more you know I suppose.Christachristabel
A
1

I faced the similar issue, this problem occurs when your Controller method return type and ExceptionHandler return types are not same. Make sure you have exactly same return types.

Controller method:

@RequestMapping(value = "/{id}", produces = "application/json", method = RequestMethod.POST)
public ResponseEntity<?> getUserById(@PathVariable String id) throws NotFoundException {
    String response = userService.getUser(id);
    return new ResponseEntity(response, HttpStatus.OK);
}

Advice method:

@ExceptionHandler(NotFoundException.class)
public ResponseEntity<?> notFoundException(HttpServletRequest request, NotFoundException e) {
    ExceptionResponse response = new ExceptionResponse();
    response.setSuccess(false);
    response.setMessage(e.getMessage());
    return new ResponseEntity(response, HttpStatus.NOT_FOUND);
}

As you can see return types in both the classes are same ResponseEntity<?>.

Anthe answered 1/12, 2016 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.