Spring @ExceptionHandler does not work with @ResponseBody

后端 未结 7 1554
南笙
南笙 2020-11-29 23:45

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 se

7条回答
  •  失恋的感觉
    2020-11-30 00:50

    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 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();
    }
    }
    

提交回复
热议问题