首页 > 解决方案 > spring-boot如何在基于Jax-RS响应Httpstatus的try块中抛出多个自定义异常

问题描述

我有这样的事情:

@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public class MyCustomExceptionA extends RuntimeException {
    public MyCustomExceptionA(String message)  {
        super(message);
    }
}
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class MyCustomExceptionB extends RuntimeException {
    public MyCustomExceptionA(String message){
        super(message);
    }
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public class MyCustomExceptionC extends RuntimeException {
    public MyCustomExceptionA(String message)  {
        super(message);
    }
}
@ControllerAdvice
public class SomeClass  {
    @ExceptionHandler(MyCustomExceptionA.class)
    public ResponseEntity<ExceptionResponse> method1(MyCustomExceptionA  ex){
        ExceptionResponse response = new ExceptionResponse(401, ex.getMessage())
    return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED);
  }

  method2 for MyCustomExceptionB

  method3 for MyCustomExceptionC
}

我正在打一个 Jax-RS 休息电话以获得响应

try{
    Response response = ClientBuilder.newCLient().target("someURL").path("somePath").get();

    if (response.getStatus() == 400){
        throw new MyCustomExceptionB("some Error message") <-- this don't get thrown
    }else if (response.getStatus() == 401){
        throw new MyCustomExceptionA("some Error message") <-- this don't get thrown
    }else if (response.getStatus() == 404){
        throw new MyCustomExceptionC("some Error message")  <-- this don't get thrown   
}catch(Exception ex){
    log.error("something happened ....")
    throw new Exception("message")                  <-- this overrides above exceptions
}

当我尝试为 400、401 或 404 抛出自定义异常时,它仍然从 catch 块中抛出异常。为什么?我通过它进行了调试,它转到了相应的状态码(400、401 或 404),但最后仍然从 catch 块抛出异常 --> 我做错了什么!

标签: javaspring-bootexceptionjax-rstry-catch

解决方案


catch 块捕获 try 块内的代码抛出的异常。这就是为什么在 if else 链中抛出异常之后运行 catch 块内的代码的原因。

我建议您在进行 Spring Boot 之前熟悉异常的基础知识。

try{
  //potentially dangerous code here.
}catch(Exception ex){
  //Catches all Exceptions thrown in try block.
  //Handle ex.
}

推荐阅读