【问题标题】:How to return 404 not found in json format using restful api in java?java - 如何在java中使用restful api以json格式返回404?
【发布时间】:2021-12-21 22:14:24
【问题描述】:

如果 uri 不匹配,我想为 restful api 实现一个异常处理程序。
例如:
url 是 localhost:8080\test\generateNumber 将返回 {"response_code":"200"}



如果网址错误,例如:
localhost:8080\test\generateNumber2 将返回 {"response_code":"404","message":"uri not found"}

我不知道该怎么做。有人可以帮忙吗?

【问题讨论】:

  • 我希望这会有所帮助Check it
  • 不是我想要的

标签: java rest spring-mvc


【解决方案1】:

我猜你正在使用 Spring?

在这种情况下,您可以像这样使用@ExceptionHandler:

@RestController
public class Example1Controller {

    @GetMapping(value = "/testExceptionHandler", produces = APPLICATION_JSON_VALUE)
    public Response testExceptionHandler(@RequestParam(required = false, defaultValue = "false") boolean exception)
            throws BusinessException {
        if (exception) {
            throw new BusinessException("BusinessException in testExceptionHandler");
        }
        return new Response("OK");
    }

    @ExceptionHandler(BusinessException.class)
    public Response handleException(BusinessException e) {
        return new Response(e.getMessage());
    }

}

并收到一条消息作为回应。

更多 - 在this manual

【讨论】:

    猜你喜欢
    • 2019-09-20
    • 2016-10-14
    • 2023-03-06
    • 2014-06-13
    • 1970-01-01
    • 2018-09-29
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多