Spring控制器中没有方法映射时如何抛出错误信息

问题描述 投票:0回答:1

当Spring控制器中没有方法映射时如何抛出错误消息。 在下面的示例中 GET /api/v1/foos 不存在,有没有办法抛出通用消息(比如 api/v1/foos 不存在)而不是默认消息。

{{base_url}}/fa/api/v1/foos/
{
    "message": "No static resource api/v1/foos.",
    "status": 500,
    "timestamp": "2024-02-29T12:58:50.813294104"
}
java spring-boot spring-mvc spring-data-rest spring-validation
1个回答
0
投票

您可以在 ExceptionController 中定义全局元素或任何您想要的名称:

@ControllerAdvice 
public class GlobalExceptionHandler 
{

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleMethodNotSupportedException(HttpRequestMethodNotSupportedException ex) {
        return new ResponseEntity<>("The requested method does not exist.", HttpStatus.NOT_FOUND);
    }
        @ExceptionHandler(NoSuchMethodException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity<String> handleNoSuchMethodException(NoSuchMethodException ex) {
        return new ResponseEntity<>("The requested method does not exist.", HttpStatus.NOT_FOUND);
    }

}

您可以使用自定义类,将参数发送到这些类中,或者仅使用字符串(作为参数)作为您想要通过这些默认异常类发送的消息。

© www.soinside.com 2019 - 2024. All rights reserved.