[英]NoSuchElementException @ExceptionHandler in SpringBoot not working
我在 SpringBoot 中創建了一個自定義異常處理程序
@RestControllerAdvice
public class DataApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(NoSuchElementException.class)
public final void **handleNoSuchElementException**(NoSuchElementException ex) {
System.err.println("This is throwing :"+ex.getMessage());
}
...
@ExceptionHandler({ Exception.class })
public ResponseEntity<Object> **handleAll**(final Exception ex) {
...
並拋出異常
throw new NoSuchElementException("SomelogicalDescription");
但是每次我拋出這個 NoSuchElementException 時,都會執行 handleAll 而不是 handleNoSuchElementException。
我可能會遺漏一些非常微不足道的東西。 幫我找出來。
***To change NoSuchElementException with NotFoundException does not make any difference.***
看起來您@RestControllerAdvice
活動。
注意:如果配置了適當的 HandlerMapping-HandlerAdapter 對(例如 RequestMappingHandlerMapping-RequestMappingHandlerAdapter 對,這是 MVC Java 配置和 MVC 命名空間中的默認值),則會處理 @RestControllerAdvice。 休息控制器建議
改用@ControllerAdvice
。 控制器建議
你有一個void
處理程序 - 那么你為什么期待回應?
你在那里返回什么? 應該是這樣的:
@ControllerAdvice
public class InvalidValuesExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler({ InvalidValuesException.class })
protected ResponseEntity<Object> handleInvalidRequest(RuntimeException exc, WebRequest request) {
InvalidValuesException ive = (InvalidValuesException) exc;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
BasicResultMessage msg = new BasicResultMessage(ive.getDataId(),
ive.getMessage());
SendDataResult result = new SendDataResult(false, msg);
return handleExceptionInternal(exc, result, headers, HttpStatus.BAD_REQUEST, request);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.