您好我需要使用自定义状态抛出自定义错误。响应状态应始终为200/201。请帮我解决此问题。下面给出的当前状态
{
"timestamp": "2017-03-30T05:59:56.010+0000",
"status": 400,
"error": "Bad Request",
"exception": "custom exception",
"message": "custom message",
"path": "/api/sjsdj"
}
我期待的回应是
{
"timestamp": "2017-03-30T05:59:56.010+0000",
"status": 600,
"error": "custom error",
"exception": "web.rest.errors.custom exception",
"message": "custom message",
"path": "/api/hgdsh/3"
}
答案 0 :(得分:0)
您可以使用@ExceptionHandler
。
使用@ControllerAdvice
注释的方法创建一个@ExceptionHandler
,缓存您的自定义异常/通用异常并返回您的自定义状态/消息等。
示例:
@ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
ErrorResponse errorResponse = new ErrorResponse(ex);
return new ResponseEntity<Object>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}