【问题标题】:How to throw NoHandlerFoundException if path param is not Long in springboot如果路径参数在 Spring Boot 中不是 Long,如何抛出 NoHandlerFoundException
【发布时间】:2023-04-07 18:10:01
【问题描述】:

目前有如下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);
}

}

【问题讨论】:

  • 访问此链接可能会对您有所帮助link

标签: java spring-boot spring-mvc exception controller-advice


【解决方案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);
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2021-09-16
    • 2019-01-24
    • 1970-01-01
    • 2022-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多