休息服务中的 Spring Boot 自定义异常
2022-09-04 07:32:30
我已经在基于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;
}
}
和自定义服务例外情况:
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"
}
但字段错误代码未显示在 JSON 响应中。
那么,如何在应用程序中定义自定义异常响应。