[英]Spring-boot - how to use both Resteasy JAX-RS and Spring MVC controllers
[英]spring-boot how to throw multiple custom exception in try block based on Jax-RS response Httpstatus
我有這樣的事情:
@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 rest 電話以獲得響應
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 引導之前熟悉異常的基礎知識。
try{
//potentially dangerous code here.
}catch(Exception ex){
//Catches all Exceptions thrown in try block.
//Handle ex.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.