处理客户端服务器

时间:2018-04-09 07:14:47

标签: rest spring-boot exception-handling

我正在尝试学习如何在API服务器中处理异常,因此我按照this在他为鸟类构建API的地方,他终于达到了这样的API:

@GetMapping(value = "/params")
public Bird getBirdRequestParam(@RequestParam("birdId") Long birdId) throws EntityNotFoundException {
    Bird bird = birdRepository.findOne(birdId);
    if(bird == null){
        throw new EntityNotFoundException(Bird.class, "id", birdId.toString());
    }
    return bird;
}

并且ControllerAdvice有一个方法:

@ExceptionHandler(EntityNotFoundException.class)
protected ResponseEntity<Object> handleEntityNotFound(
        EntityNotFoundException ex) {
    ApiError apiError = new ApiError(NOT_FOUND);
    apiError.setMessage(ex.getMessage());
    return buildResponseEntity(apiError);
}

响应将像这样的鸟

{
"id": 1,
"scientificName": "Atlantic canary",
"specie": "serinus canaria",
"mass": 10,
"length": 11
}

或像这样的例外细节:

{
"apierror": {
    "status": "NOT_FOUND",
    "timestamp": "09-04-2018 10:11:44",
    "message": "Bird was not found for parameters {id=2}"
}

但问题出在我的服务器与API联系

我正在使用:

public void gett(@RequestParam Long id) {
    ResponseEntity<Bird> responseEntity = restTemplate.getForEntity("http://localhost:8181/params" + id, Bird.class);
    bird = responseEntity.getBody();
    model.addAttribute("birdform", bird);
    return "bird";
}

getForEntity正在等待鸟体的响应,但是服务器中可能会抛出异常,响应可能是错误的json。

如何在我的客户端服务器中处理此问题?

换句话说,

如何在我的客户端服务器中知道api服务器以json格式抛出异常。???

我试图在&#34;对象&#34;变量,然后尝试知道是否是#34;&#34;&#34;表达式就像这段代码

@GetMapping("/getbird")
public String getAll(@RequestParam Long id, Model model) {
    ResponseEntity<Object> responseEntity = restTemplate.getForEntity("http://localhost:8181/api/bird/getone?id=" + id, Object.class);
    if (responseEntity.getBody() instanceof Bird.class) {
        Bird bird= (Bird) responseEntity.getBody();
        model.addAttribute("Bird", bird);
        return "bird-form";
    }
    else{
        // something else
        return "someview";
    }
}

但首先它没有用(总是返回false的实例)

第二件事是,这对我的所有控制器来说都是一项艰苦的工作。动作。

我希望我能清楚地解释我的问题。

感谢....

2 个答案:

答案 0 :(得分:0)

您不需要检查响应的正文以查看是否有错误。如果您获得4XX响应,HttpClientErrorException(和其他方法)会抛出HttpServerErrorException,如果您从通话中获得5XX响应,则会@ControllerAdvice

要捕获这些异常,您可以使用适当的异常处理方法定义@ControllerAdvice class GlobalControllerExceptionHandler { @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 500 @ExceptionHandler(HttpClientErrorException.class) public ApiError handle4xxFromClient(HttpClientErrorException ex) { // construct and return a custom ApiError object } }

FOR /F %%A IN ('WMIC Path Win32_LocalTime Get Day^,Month^,Year /value ^|find "="') do set "_%%A"
set version2=%11.%_Year:~2,2%.%_Month%.%_Day%
echo %version2%

有关详细信息,请参阅https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

答案 1 :(得分:0)

两种解决方案:

  1. 在reste模板中使用自定义实现错误处理程序。 restTemplate.setErrorHandler(customerErrorHandler)

  2. 使用http status,如果从正在查询的服务器获取错误的http状态,则rest模板将引发异常。捕获异常并从异常中获取ApiError对象,然后抛出自己的异常,这将由客户端服务器中的异常处理程序处理。

  3. 要使这些解决方案正常工作,您正在查询的服务器需要在发生错误时发送正确的http状态代码。