首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Spring REST将字段添加到404共振代码

Spring REST将字段添加到404共振代码
EN

Stack Overflow用户
提问于 2018-05-31 15:51:55
回答 1查看 228关注 0票数 3

使用2018年5月的最新Spring Boot。我已经创建了一个这样的404响应。

代码语言:javascript
复制
@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响应

代码语言:javascript
复制
{
    "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“会自动出现在响应中,如下所示

代码语言:javascript
复制
{
    "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方法的通知)吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-31 17:17:43

在Spring中使用@ControllerAdvice和@ExceptionHanlder。这就是异常控制器。实际上,您将创建自定义异常控制器并定义异常。

这是为您提供的示例代码:

代码语言:javascript
复制
@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);
    }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50619324

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档