目前,有一個 GetMapping 如下
@GetMapping(value = "/{id}")
public ResponseEntity<Dog> getTrainById(@PathVariable Long id) {
Dog dog= animalService.getAnimalById(id);
return new ResponseEntity<>(Dog , HttpStatus.OK);
}
現在如果有人訪問 http://localhost:8080/api/animal/1,它會回傳動物。
但是如果有人在沒有 Long 變數作為路徑引數的情況下訪問此端點,我需要拋出 NoHandlerFoundException,這意味著像這樣 http://localhost:8080/api/animal/asdsad
如果有人能告訴我實作這一目標的方法,那將不勝感激
我也有如下全域例外處理
@ControllerAdvice
public class DemoExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<GenericResponse> customHandleNotFound(Exception ex, WebRequest request)
{
return new ResponseEntity<>(new GenericResponse(ex.getMessage(), null), HttpStatus.NOT_FOUND);
}
@Override
protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
return new ResponseEntity<>(new GenericResponse("invalid endpoint", null), HttpStatus.METHOD_NOT_ALLOWED);
}
}
uj5u.com熱心網友回復:
在這種情況下,請求無法決議為控制器方法的引數型別,它會拋出MethodArgumentTypeMismatchException。
所以解決問題最有效的方法是MethodArgumentTypeMismatchException直接想著怎么處理,而不是想著怎么讓它重新拋出NoHandlerFoundException。所以你可以簡單地創建一個@ControllerAdvice來處理MethodArgumentTypeMismatchException:
@ControllerAdvice
public class DemoExceptionHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<Object> handle(MethodArgumentTypeMismatchException ex) {
return new ResponseEntity<>( GenericResponse("invalid endpoint", null), HttpStatus.METHOD_NOT_ALLOWED);
}
}
它將應用于所有拋出此類例外的控制器。如果您只希望它申請特定控制器而不是全域,您可以這樣做:
@RestController
@RequestMapping("/foo")
public class FooController {
@GetMapping(value = "/{id}")
public ResponseEntity<Dog> getTrainById(@PathVariable Long id) {
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public ResponseEntity<Object> handleMethodArgumentTypeMismatchException() {
return new ResponseEntity<>( GenericResponse("invalid endpoint", null), HttpStatus.METHOD_NOT_ALLOWED);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414602.html
標籤:
