【问题标题】:Throwing custom errors as Json when a parameter is invalid当参数无效时将自定义错误作为 Json 抛出
【发布时间】:2022-01-22 17:55:29
【问题描述】:

我正在开发一个 API,需要抛出如下所示的异常

"error": "sortBy parameter is invalid"
}

如果 sort by 参数不是我预先确定的值之一, 我有一些参数可以做到这一点 这是我的控制器的样子

@GetMapping("/api/posts")

    public ResponseEntity<List<Post>> getPostResponse(@RequestParam String tag, Optional<String> sortBy,
            Optional<String> direction) throws InvalidSortBy {

        RestTemplate postResponseTemplate = new RestTemplate();
        URI postUri = UriComponentsBuilder.fromHttpUrl("urlHere")
                                          .queryParam("tag", tag)
                                          .queryParamIfPresent("sortBy", sortBy)
                                          .queryParamIfPresent("direction", direction)
                                          .build()
                                          .toUri();

        ResponseEntity<PostResponse> response = postResponseTemplate.getForEntity(postUri, PostResponse.class);
        ResponseEntity<List<Post>> newResponse = responseService.createResponse(response, sortBy, direction);   
    
         return newResponse;

    }
}

我删除了 url,但它适用于对传入数据进行排序,但我需要验证并抛出正确的错误,我真的不确定如何以所需的格式执行它,如 json,任何帮助表示赞赏

【问题讨论】:

    标签: java spring spring-boot api error-handling


    【解决方案1】:

    首先你需要处理你的异常并根据错误解决它,我建议你为已知的应用程序异常提出错误代码并在你的异常处理程序中解决它们(使用@ControllerAdvice或@RestControllerAdvice),一旦你翻译相应消息的错误代码将它们作为 json 发送,您可以参考下面的线程以获取有关以下 SO 线程的更多详细信息

    How to throw an exception back in JSON in Spring Boot

    @ExceptionHandler

    @ExceptionHandler 告诉 Spring 我们应该使用哪些方法 为给定的异常调用

    @RestControllerAdvice

    使用包含@ControllerAdvice 的@RestControllerAdvice 将周围的类注册为每个 @Controller 应该是的东西 知道,并 @ResponseBody 告诉 Spring 呈现该方法的 以 JSON 格式响应

    【讨论】:

      猜你喜欢
      • 2019-01-25
      • 1970-01-01
      • 2019-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-28
      相关资源
      最近更新 更多