弹簧启动 404 错误自定义错误响应 ReST

2022-09-01 11:33:44

我正在使用Spring boot来托管REST API。我希望始终发送JSON响应,而不是具有标准错误响应,即使浏览器正在访问URL和自定义数据结构。

我可以使用@ControllerAdvice执行此操作,并为自定义异常@ExceptionHandler。但是我找不到任何好的方法来为404和401等标准和处理错误做到这一点。

有没有关于如何做到这一点的良好模式?


答案 1

对于那些不想使用的Spring Boot 2用户@EnableWebMvc

应用程序.属性

server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

控制器建议

@RestControllerAdvice
public class ExceptionResolver {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public HashMap<String, String> handleNoHandlerFound(NoHandlerFoundException e, WebRequest request) {
        HashMap<String, String> response = new HashMap<>();
        response.put("status", "fail");
        response.put("message", e.getLocalizedMessage());
        return response;
    }
}


答案 2

它是为我工作,如果@RestControllerAdvice与弹簧靴

spring.mvc.throw-exception-if-no-handler-found=true
server.error.whitelabel.enabled=false
spring.resources.add-mappings=false

@RestControllerAdvice
public class ErrorHandlerController {

@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND )
public String handleNotFoundError(NoHandlerFoundException ex) {
    return "path does not exists";
}
}