Spring REST 添加字段到 404 响应代码
Spring REST add field to 404 resonse code
使用截至 2018 年 5 月的最新 Spring 引导。我已经创建了这样的 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
}
只是 方法(就像对 getErrorId 方法的注解)在响应中包含 属性 "errorId" 吗?
您在 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);
}
}
Byeon0gam 所说的一切都很好,在这里我将展示另一种方式,这意味着在维护代码方面有一点不同。
我们已经知道,
我们可以通过 4 种方式处理 spring-rest 中的异常:
1. 使用 ResponseEntity Class。
2. 使用@ResponseStatus 注解。
3.使用@ExceptionHandler() 注解。
4. Return错误表示而不是默认的HTML错误页面。
通过使用 Those,我们只能在方法或 Class 级别处理异常。
但是,如果您想在整个应用程序中处理全局方式,请按照以下步骤操作。
处理全局异常:
处理我们应用程序中的所有异常,
首先我们需要创建一个class,然后我们需要在class 之上使用@ControllerAdvice 注解。在 class body 中,我们可以处理应用程序中引发的异常。
在 Class 中,我们将创建异常处理方法,在每个方法之上,我们将使用 @ExceptionHandler() 注释来导航异常和处理。
如果我们的应用程序中出现任何异常,基于@ExceptionHandler(“argument”) 注释参数,将调用异常处理方法并执行剩余的处理代码。
@ControllerAdvice
public class SpringRestGlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<?> exceptionHandler(HttpServletRequest req, Exception e)
{
JSONObject obj =new JSONObject();
obj.put("msgTxt","Unknown Server Error, Please Contact Admin." );
obj.put("reqUrl", req.getRequestURI());
obj.put("stackTrace", e.toString());
obj.put("isErrorFlag", true);
obj.put("httpStatusCode", HttpStatus.OK.value());
gstcDaoi.saveExceptionOrErrorLog(prepareTGstcExceptionOrErrorLogObject(obj));
e.printStackTrace();
return new ResponseEntity<>(obj, HttpStatus.OK);
}
使用截至 2018 年 5 月的最新 Spring 引导。我已经创建了这样的 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
}
只是 方法(就像对 getErrorId 方法的注解)在响应中包含 属性 "errorId" 吗?
您在 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);
}
}
Byeon0gam 所说的一切都很好,在这里我将展示另一种方式,这意味着在维护代码方面有一点不同。
我们已经知道, 我们可以通过 4 种方式处理 spring-rest 中的异常: 1. 使用 ResponseEntity Class。 2. 使用@ResponseStatus 注解。 3.使用@ExceptionHandler() 注解。 4. Return错误表示而不是默认的HTML错误页面。
通过使用 Those,我们只能在方法或 Class 级别处理异常。 但是,如果您想在整个应用程序中处理全局方式,请按照以下步骤操作。
处理全局异常: 处理我们应用程序中的所有异常, 首先我们需要创建一个class,然后我们需要在class 之上使用@ControllerAdvice 注解。在 class body 中,我们可以处理应用程序中引发的异常。 在 Class 中,我们将创建异常处理方法,在每个方法之上,我们将使用 @ExceptionHandler() 注释来导航异常和处理。 如果我们的应用程序中出现任何异常,基于@ExceptionHandler(“argument”) 注释参数,将调用异常处理方法并执行剩余的处理代码。
@ControllerAdvice
public class SpringRestGlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<?> exceptionHandler(HttpServletRequest req, Exception e)
{
JSONObject obj =new JSONObject();
obj.put("msgTxt","Unknown Server Error, Please Contact Admin." );
obj.put("reqUrl", req.getRequestURI());
obj.put("stackTrace", e.toString());
obj.put("isErrorFlag", true);
obj.put("httpStatusCode", HttpStatus.OK.value());
gstcDaoi.saveExceptionOrErrorLog(prepareTGstcExceptionOrErrorLogObject(obj));
e.printStackTrace();
return new ResponseEntity<>(obj, HttpStatus.OK);
}