java - 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 块抛出异常 --> 我做错了什么!
解决方案
catch 块捕获 try 块内的代码抛出的异常。这就是为什么在 if else 链中抛出异常之后运行 catch 块内的代码的原因。
我建议您在进行 Spring Boot 之前熟悉异常的基础知识。
try{
//potentially dangerous code here.
}catch(Exception ex){
//Catches all Exceptions thrown in try block.
//Handle ex.
}
推荐阅读
- angular - 使用 *ngFor 从 ng-container 只向下切换一个 div
- java - 通过 Jtds 连接到 Sql Server Local Db
- xslt - 使用 DocBook/XLST-FO 生成带有章节编号的页面引文
- r - 如何将原子向量转换为可以在 R 中使用“$”符号的递归向量?
- sql - Oracle SQL 将多行聚合为单行
- java - 简单地调用 parallelStream 是否并行运行任务?
- java - 可选的
映射函数返回空 - php - 当商店用户在 Sylius 进行电子邮件确认时如何收听事件?
- python - Python - 从外部函数更新窗口类中的标签文本
- javascript - 无法在“窗口”GoogleTagManager 上执行“postMessage”