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

java基础(六):springboot统一异常处理

2018-09-29 19:46 483 查看

eg:

@Slf4j
@ControllerAdvice
public class WebExceptionHandler {

/**
* 文件大小限制
*/
@Value("${upload.file.size}")
private String fileSize;

/**
*  web 统一异常处理
* @param request
* @param ex
* @return
*/
@ExceptionHandler(value = {Exception.class, Throwable.class})
public @ResponseBody
RespBody handleException(HttpServletRequest request, Throwable ex) {
log.error(ex.getMessage(), ex);
// 自定义异常类型
if (ex instanceof BussinessException) {
BussinessException be = (BussinessException) ex;
return R.info(be.getRespCode(), be.getRespMsg());
}
// 上传文件大小异常
if (ex instanceof MultipartException) {
return R.info(ResultInfo.WEB_COMMON_FILASIZE_LIMIT_0003.getCode(),
ResultInfo.WEB_COMMON_FILASIZE_LIMIT_0003.getCacheMsg(fileSize));
}
// 通用错误类型
return R.info(ResultInfo.WEB_SYS_ERROR);
}

}

一:定义全局异常处理类
1、使用@ControllerAdvice定义统一的异常处理类,可以不用在每个Controller中逐个定义异常处理方式
2.@ExceptionHandler 用来定义函数针对的异常类型,controller通过抛出的异常类型匹配

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: