我有这样的东西:
@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块抛出Exception->我在做什么错了!!
catch块捕获try块中的代码引发的异常。这就是为什么在if else链中抛出异常之后运行catch块中的代码的原因。
我建议您在进行Spring Boot之前熟悉异常的基本知识。
try{
//potentially dangerous code here.
}catch(Exception ex){
//Catches all Exceptions thrown in try block.
//Handle ex.
}