Spring @ExceptionHandler,@ ResponseBody不会序列化/编组响应

时间:2016-08-18 15:55:48

标签: spring rest spring-mvc

我有一个非常简单的Spring rest控制器,如下所示:

@RequestMapping("/management")
@RestController
public class ManagementController {

    @Autowired
    private ManagementService managementService;

    @ExceptionHandler(DuplicateEntityException.class)
    @ResponseStatus(code = HttpStatus.CONFLICT)
    public ErrorDetail handleDuplicateEntityException(DuplicateEntityException ex) {
        return new ErrorDetail(ex.getMessage(), HttpStatus.CONFLICT.value());
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    @ResponseStatus(code = HttpStatus.CREATED)
    public User createUser(@RequestBody User user) {
        return managementService.createUser(user);
    } 
}

和ErrorDetail类...

@XmlRootElement(name = "error")
@XmlAccessorType(XmlAccessType.FIELD)
public class ErrorDetail {

    @XmlElement(name = "message")
    private String message;

    @XmlAttribute(name = "status")
    private int status;

    public ErrorDetail(String message, int status) {
        super();
        this.message = message;
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public int getStatus() {
        return status;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setStatus(int status) {
        this.status = status;
    }

}

和自定义异常,AAAException扩展了RuntimeException。

public class DuplicateEntityException extends AAAException {

    private static final long serialVersionUID = 4223773548694193141L;

    public DuplicateEntityException(String message) {
        super(message);
    }

    public DuplicateEntityException(String message, Throwable cause) {
        super(message, cause);
    }

}

但是@ExceptionHandler不会编组ErrorDetail对象我只得到500,我可以从这个方法返回一个字符串,它可以工作。我正在发送正在通过createUser方法正确解组和编组的application / xml,我无法理解为什么同样不能为@ExceptionHandler工作。

我使用的是Spring 4.2.6。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

您似乎已在exception handler中添加了controller方法,因为如果您从exception本身获得controller,则会触发该方法。使用单独的类进行异常处理ex:

@ControllerAdvice
public class GlobalExceptionController {

@ExceptionHandler(DuplicateEntityException.class)
@ResponseBody
public ErrorDetail handleDuplicateEntityException(DuplicateEntityException ex) {
   ExceptionRepresentation  body = new ExceptionRepresentation(ex.getMessage());
   HttpStatus responseStatus = HttpStatus.CONFLICT;
   return new ResponseEntity<ExceptionRepresentation>(body,responseStatus);
}

此处使用@ControllerAdvice将对每个exception

应用controller.处理

并且最重要的部分是您的方法应该抛出异常以便@ExceptionHandler更改您的方法签名。

 public User createUser(@RequestBody User user) throw DuplicateEntityException{
    throw new DuplicateEntityException();
    }

答案 1 :(得分:0)

我在调试代码后尴尬地说,问题是ErrorDetail类缺少默认构造函数: - (