gpt4 book ai didi

java - Spring REST 将字段添加到 404 响应代码

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:21 24 4
gpt4 key购买 nike

截至 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
}

在响应中是否有一种简单的方式(比如对 getErrorId 方法的注解)?

最佳答案

您在 Spring 中使用@ControllerAdvice 和@ExceptionHanlder。那是异常 Controller 。事实上,您将创建自定义异常 Controller 并定义异常。

这是给你的示例代码:

@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);
}

}

关于java - Spring REST 将字段添加到 404 响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50619324/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com