【Java】【Spring】SpringBoot中添加异常处理器

异常处理器可以在服务器代码报错,路径不存在,请求方法错误,参数校验失败时,对Response进行拦截,将指定的提示信息返回给客户端


@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseEntity onValidFail(Exception e, HttpServletRequest request, HttpServletResponse response) {
        return new ResponseEntity(HttpResponse.fail("无效的请求参数").stringfy(), HttpStatus.OK);
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public ResponseEntity onMethodNotFound(Exception e, HttpServletRequest request, HttpServletResponse response) {
        return new ResponseEntity(HttpResponse.fail("无效的请求方法").stringfy(), HttpStatus.OK);
    }

    @ExceptionHandler(value = {NoHandlerFoundException.class})
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseEntity onHandlerNotFound(Exception e, HttpServletRequest request, HttpServletResponse response) {
        return new ResponseEntity(HttpResponse.fail("无效的请求路径").stringfy(), HttpStatus.OK);
    }

    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseEntity onServerError(Exception e, HttpServletRequest request, HttpServletResponse response) {
        return new ResponseEntity(HttpResponse.fail("服务器发生异常").detail(e.getMessage()).stringfy(), HttpStatus.OK);
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity onUnknownException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        return new ResponseEntity(HttpResponse.fail("未知异常").detail(e.getMessage()).stringfy(), HttpStatus.OK);
    }
}

Spring框架默认产生404时,会跳向一个错误页面,并不会抛出Exception
所以需要在application.properties中指定,将404转化为异常抛出,才能被ExceptionHandler捕获
如果是yml等其它格式的配置文件,修改一下格式即可,字段都是一样的


#404转异常抛出
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

你可能感兴趣的:(java,SpringBoot)