spring 为什么抛出400时没有捕获HttpStatusCodeException?

2ic8powd  于 2022-10-30  发布在  Spring
关注(0)|答案(2)|浏览(131)

c考虑下面的类,当rest调用抛出400 BAD_REQUEST时,我希望捕捉到HttpStatusCodeException,但它却捕捉到了意外错误Exception并抛出了内部服务器错误。为什么在抛出“BAD_REQUEST”时没有捕捉到HttpStatusCodeException?

class Abc {

     @Autowired
     RestTemplate template;

     void connect(){

        ResponseEntity<String> response;

        try{
            response=restTemplate.postForEntity("url", HTTP_ENTITY, String.class);

        } catch( HttpStatusCodeException ex){
             throws new CustomErrorResponse(ex.getStatusCode());
        } catch (Exception ex){
             throws new CustomErrorResponse(Internal_Server_Error);
        }
      }

    }

JUnit测试用例

when(restTemplate.postForEntity(anyString(),any(),eq(String.class))).thenThrow(new CustomErrorResponse(HttpStatus.BAD_REQUEST));

但抛出了内部服务器

sq1bmfud

sq1bmfud1#

如果connect方法可以有不同的返回类型,最简单的方法就是返回一个ResponseEntity并将状态代码传递给它。

ResponseEntity<Object> connect(){

        ResponseEntity<String> response;

        try{
            response=restTemplate.postForEntity("url", HTTP_ENTITY, String.class);

        } catch( HttpStatusCodeException ex){
             response = new ResponseEntity<>("There was an issue with the POST call.", ex.getStatusCode());
        } catch (Exception ex){
             throws new CustomErrorResponse(Internal_Server_Error);
        }
        return responseEntity;
     }

相关问题