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