如何使用resttemplate和springboot捕获自定义异常?

时间:2019-06-05 09:36:23

标签: spring-boot

我想在服务器中抛出定制异常并在客户端中捕获它,但是似乎定制异常已转换为HttpServerErrorException。

TestController.java

@RestController
public class TestController {

    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public String test()  {
            throw new PasswdException("password err");
    }
}

PasswdException.java

public class PasswdException extends RuntimeException {
    public PasswdException(String msg) {
        super(msg);
    }
}

RestTest.java

public class RestTest {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        try {
           String s = restTemplate.postForObject("http://localhost:8080/test", null, String.class);
        } catch (Exception e) {
            if(e instanceof PasswdException){
                System.out.println("..........");
                //do sth
            }
        }

    }
}

预期:客户端异常实例PasswdException,但实际的异常是HttpServerErrorException

1 个答案:

答案 0 :(得分:0)

就REST而言这是不可能的,但是您可以通过以下方式定义合同来实现: 1.为您的异常定义HTTP错误状态代码,例如(BAD_REQUEST相关性更高,您可以选择自己喜欢的任何一种):

@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Wrong password")
public class PasswdException extends RuntimeException {
    private static final long serialVersionUID = 1L;
}
  1. RestTest(客户端)代码应使用类似以下内容检查此HTTP错误状态:

    if(resp.getStatus().equals(HttpStatus.BAD_REQUEST))