【发布时间】:2014-12-16 11:51:31
【问题描述】:
我在基于 Spring Boot 的 Rest 服务中定义了一个全局异常处理:
@ControllerAdvice
public class GlobalExceptionController {
private final Logger LOG = LoggerFactory.getLogger(getClass());
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "Internal application error")
@ExceptionHandler({ServiceException.class})
@ResponseBody
public ServiceException serviceError(ServiceException e) {
LOG.error("{}: {}", e.getErrorCode(), e.getMessage());
return e;
}
}
还有一个自定义的 ServiceException:
public class ServiceException extends RuntimeException {
private static final long serialVersionUID = -6502596312985405760L;
private String errorCode;
public ServiceException(String message, String errorCode, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
}
// other constructors, getter and setters omitted
}
到目前为止一切顺利,当触发异常时,控制器会正常工作并响应:
{
"timestamp": 1413883870237,
"status": 500,
"error": "Internal Server Error",
"exception": "org.example.ServiceException",
"message": "somthing goes wrong",
"path": "/index"
}
但 errorCode 字段未显示在 JSON 响应中。
那么如何在我的应用程序中定义自定义异常响应。
【问题讨论】:
标签: java rest exception-handling spring-boot