0

目前,有一个 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);
}

}

4

1 回答 1

1

在这种情况下,请求无法解析为控制器方法的参数类型,它会抛出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);
    }

}
于 2022-01-13T21:13:38.750 回答