您的位置:首页 > 编程语言 > Java开发

springBoot 全局异常统一处理

2019-03-27 18:50 771 查看
版权声明:本文为博主原创文章,如需转载请注明原文出处: https://blog.csdn.net/u010979642/article/details/88852459

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());

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

@ExceptionHandler(NullPointerException.class)
@ResponseStatus(HttpStatus.ACCEPTED)
@ResponseBody
public AIResponse exceptionHandler(NullPointerException nullPointerException) {
LOGGER.info("nullPointerException: " + nullPointerException.getMessage());

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: