我有以下ExceptionHandler:
@ExceptionHandler(ValueNotAllowedException.class)
void handleBadRequests(HttpServletResponse response, ValueNotAllowedException ex) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
}
(来自项目中另一个控制器的响应。我的回答应该类似)
{
"timestamp": 1476462787425,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "Could not read document: Start date should be before or equal end date\n at [Source: java.io.PushbackInputStream@47842b65; line: 23, column: 16] (through reference chain: com.instinctools.mailtracker.endpoints.dto.QueryFilterDTO[\"startDate\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Start date should be before or equal end date\n at [Source: java.io.PushbackInputStream@47842b65; line: 23, column: 16] (through reference chain: com.instinctools.mailtracker.endpoints.dto.QueryFilterDTO[\"startDate\"])",
"path": "/statistics/clicks"
}
答案 0 :(得分:2)
创建一个基础Error
对象(正确注释),该对象将返回UI
。
class Error {
private String timestamp;
private Integer status;
private String error;
private String exception;
private String message;
private String path;
//constructors here, whatever
.....
}
..然后用这样的东西改变你的ExceptionHandler:
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(ValueNotAllowedException.class)
@ResponseBody Error handleBadRequest(HttpServletRequest req, Exception ex) {
//Create and return your Error object here.
return new Error(/* populate with all the stuff you need here */);
}
希望这有帮助!