使用2018年5月的最新Spring Boot。我已经创建了一个这样的404响应。
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException {
private final int errorId;
public NotFoundException(String errorMsg) {
super("-1," + errorMsg);
this.errorId = -1;
}
public NotFoundException(int errorId, String errorMsg) {
super(errorId + "," + errorMsg);
this.errorId = errorId;
}
public int getErrorId() {
return errorId;
}
}
注释@ResponseStatus(HttpStatus.NOT_FOUND)使我的NotFoundException看起来像这样的404响应
{
"timestamp":1527751944754,
"status":404,
"error":"Not Found",
"exception":"com.myapp.exception.NotFoundException",
"message":"1000,Could not find data for owner: 1234","path":"/resource/owner/1234"
}
我希望属性"getErrorId“会自动出现在响应中,如下所示
{
"timestamp":1527751944754,
"status":404,
"error":"Not Found",
"exception":"com.myapp.exception.NotFoundException",
"message":"Could not find data for owner: 1234","path":"/resource/owner/1234",
"errorId": 1000
}
在响应中拥有"errorId“属性是一种简单的方式(类似于对getErrorId方法的通知)吗?
发布于 2018-05-31 17:17:43
在Spring中使用@ControllerAdvice和@ExceptionHanlder。这就是异常控制器。实际上,您将创建自定义异常控制器并定义异常。
这是为您提供的示例代码:
@ControllerAdvice("your.package")
public class CommonExceptionHandler {
@ExceptionHandler(value = NoHandlerFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public @ResponseBody ResponseEntity<?> setNotFoundException(Exception exception) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
// this is sample map. you will make your custom model and you use exception parameter.
Map<String, String> map = new HashMap<String, String>();
map.put("timestamp", String.valueOf(new Date().getTime()));
map.put("status", HttpStatus.NOT_FOUND.toString());
map.put("error", "Not Found");
map.put("exception", exception.getMessage());
map.put("message", "Could not find data for owner: 1234");
map.put("path", "/resource/owner/1234");
map.put("errorId", "1000");
String json = mapper.writeValueAsString(map);
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(json);
}
}
https://stackoverflow.com/questions/50619324
复制相似问题