Bootstrap

Java实现全局异常统一处理

【一】介绍

全局异常处理器是一种在应用程序中几种处理异常的机制,它允许在应用程序的任何地方抛出异常时,通过集中的异常处理器进行捕获、记录和处理,而不是在每个可能跑出异常的地方都进行单独处理。

在Java应用中,特别是在使用Spring框架的项目中,全局异常处理器通常通过实现HandlerExceptionResolver 接口、使用 @ControllerAdvice 注解或实现 ErrorController 接口来实现。

【二】为什么要使用全局异常处理

如果我们不统一的处理异常,经常会在controller层有大量的异常处理的代码, 比如:

@Slf4j
@Api(value = "User Interfaces", tags = "User Interfaces")
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * http://localhost:8080/user/add .
     *
     * @param userParam user param
     * @return user
     */
    @ApiOperation("Add User")
    @ApiImplicitParam(name = "userParam", type = "body", dataTypeClass = UserParam.class, required = true)
    @PostMapping("add")
    public ResponseEntity<String> add(@Valid @RequestBody UserParam userParam) {
        // 每个接口充斥着大量的异常处理
        try {
            // do something
        } catch(Exception e) {
            return ResponseEntity.fail("error");
        }
        return ResponseEntity.ok("success");
    }
}

【三】案例实现

首先在项目下创建一个exception的包,用来存放全局异常处理器
在这里插入图片描述

【1】GlobalException

package org.xmxframework.common.exception;

public class GlobalException extends RuntimeException {
    private static final long serialVersionUID = -2429459012219984965L;

    public GlobalException(String message) {
        super(message);
    }

    public GlobalException(String message, Throwable cause) {
        super(message, cause);
    }
}

【2】GlobalExceptionHandler

其中如果发生异常,直接可以返回配置的自定义通用响应对象

@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler{
    public final Logger logger = LoggerFactory.getLogger(this.getClass());

    public GlobalExceptionHandler() {
    }

    public void doSomething(Exception e, HttpServletRequest request) {
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({HttpMessageNotReadableException.class})
    public ResponseResult handleHttpMessageNotReadableException(Exception e, HttpServletRequest request) {
        this.doSomething(e, request);
        this.logger.warn("400-参数解析失败,{},{}", e.getMessage(), request.getServletPath());
        return ResponseResult.fail("参数解析失败");
    }

    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    @ExceptionHandler({HttpRequestMethodNotSupportedException.class})
    public ResponseResult handleHttpRequestMethodNotSupportedException(Exception e, HttpServletRequest request) {
        this.doSomething(e, request);
        this.logger.warn("405-不支持当前请求方法,{},{}", e.getMessage(), request.getServletPath());
        return ResponseResult.fail("不支持当前请求方法");
    }

    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    @ExceptionHandler({HttpMediaTypeNotSupportedException.class})
    public ResponseResult handleHttpMediaTypeNotSupportedException(Exception e, HttpServletRequest request) {
        this.doSomething(e, request);
        this.logger.warn("415-不支持当前媒体类型,{},{}", e.getMessage(), request.getServletPath());
        return ResponseResult.fail("不支持当前媒体类型");
    }

    @ExceptionHandler({Exception.class})
    public ResponseResult handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
        this.doSomething(e, request);
        if (e instanceof XmxException) {
            if (e.getCause() == null) {
                this.logger.warn("业务提示,{},{}", e.getMessage(), request.getServletPath());
                response.setStatus(200);
            } else {
                this.logger.error("业务异常," + request.getServletPath(), e);
                response.setStatus(500);
            }

            return ResponseResult.fail(e.getMessage());
        } else {
            this.logger.error("系统异常," + request.getServletPath(), e);
            response.setStatus(500);
            return ResponseResult.fail("系统异常");
        }
    }
}

【3】使用

这样就可以根据参数或者其他业务逻辑来统一的返回异常,使代码更加健壮,好维护,而且看着也整洁,而且不需要进行大量的异常处理

@Slf4j
@Api(value = "User Interfaces", tags = "User Interfaces")
@RestController
@RequestMapping("/user")
public class UserController {

    /**
     * http://localhost:8080/user/add .
     *
     * @param userParam user param
     * @return user
     */
    @ApiOperation("Add User")
    @ApiImplicitParam(name = "userParam", type = "body", dataTypeClass = UserParam.class, required = true)
    @PostMapping("add")
    public ResponseEntity<UserParam> add(@Valid @RequestBody UserParam userParam) {
			   //异常处理
			   if(){
			       return new GlobalException("缺少业务参数")
			   }else(){
			       return new GlobalException("xxxxxxx")
			   }
	       return ResponseEntity.ok(userParam);
    }
}


;