springBoot 全局异常统一处理

springBoot 全局异常统一处理

 

注解说明

// 对某一类异常进行统一处理, 从而能够减少代码重复率和复杂度
@ExceptionHandler

// 异常集中处理, 更好的将业务逻辑和异常处理解耦
@ControllerAdvice

// 将某种异常映射为HTTP状态码
@ResponseStatus

 

定义全局异常捕获类

@ControllerAdvice
public class ExceptionController {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionController.class);

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ResponseBody
    public AIResponse exceptionHandler(Exception exception) {
        LOGGER.info("exception: " + exception.getMessage());

		if (exception instanceof SQLException || exception instanceof UncategorizedSQLException) {
            return AIResponse.failed("操作数据库异常");
        }

        return AIResponse.failed(exception.getMessage());
    }



    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.ACCEPTED)
    @ResponseBody
    public AIResponse exceptionHandler(NullPointerException nullPointerException) {
        LOGGER.info("nullPointerException: " + nullPointerException.getMessage());
        // 空指针异常需要打印堆栈信息
		nullPointerException.printStackTrace();
        return AIResponse.failed(nullPointerException.getMessage());
    }


}

 

测试验证

@Controller
@RequestMapping("/user")
public class UserController {
    
    @RequestMapping("query")
    @ResponseBody
    public AIResponse query(@RequestBody RequestDTO requestDTO) {
        // ...
    }
}

 

如果项目中采用 AOP, 则 AOP 中的异常要抛出, 不要捕获处理

@Component
@Aspect
@Slf4j
public class AALAop {

    @Around("execution(public * com.answer.aal.controller..*Controller.*(..))")
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result;
        Object[] args = proceedingJoinPoint.getArgs();

        result = proceedingJoinPoint.proceed(args);

		/** ERROR
        try {
            result = proceedingJoinPoint.proceed(args);
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        */

        return result;
    }
}

你可能感兴趣的:(Spring,开发笔记,笔试面试经)