java怎么统一管理异常_Spring Boot 统一异常管理

前言

在日常开发中经常会出现各种异常,怎么处理这些统一处理这些异常成为了一个问题,Spring Boot 支持多种异常处理机制,今天我们就简单的介绍一下常用的统一异常处理机制。

@ControllerAdvice方式

通过使用@ControllerAdvice 和 @ExceptionHandler定义统一的异常处理类,而不是在每个Controller中逐个定义。

HTML异常

定义统一的异常处理控制器

@ControllerAdvice

class GlobalExceptionHandler {

public static final String DEFAULT_ERROR_VIEW = "error";

@ExceptionHandler(value = Exception.class)

public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {

ModelAndView mav = new ModelAndView();

mav.addObject("exception", e);

mav.addObject("url", req.getRequestURL());

mav.setViewName(DEFAULT_ERROR_VIEW);

return mav;

}

}

复制代码定义统一的异常处理页面

统一异常处理

Error Handler

复制代码

JSON异常

定义统一的异常响应JSON

@Data

public class ErrorResult {

private Integer code;

private String message;

private String url;

private T data;

}

复制代码定义统一的异常处理控制器

@ControllerAdvice

public class GlobalExceptionHandler {

//捕获自定义业务异常

@ExceptionHandler(value = BizException.class)

@ResponseBody

public ErrorResult jsonErrorHandler(HttpServletRequest req,BizException e) throws Exception {

ErrorResult r = new ErrorResult<>();

r.setMessage(e.getMessage());

r.setCode(ErrorInfo.ERROR);

r.setUrl(req.getRequestURL().toString());

return r;

}

}

复制代码

2. BasicErrorController方式

使用这种方案,无需自己判断请求的接口是 HTML 还是 RESTful API

定义统一异常处理器

@Controller

@RequestMapping("/error")

public class GlobalErrorController extends BasicErrorController {

@Autowired

public GlobalErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties) {

super(errorAttributes, serverProperties.getError());

}

@RequestMapping(produces = "text/html")

@Override

public ModelAndView errorHtml(HttpServletRequest request,

HttpServletResponse response) {

return super.errorHtml(request, response);

}

@RequestMapping

@ResponseBody

@Override

@SuppressWarnings("unchecked")

public ResponseEntity> error(HttpServletRequest request) {

Map body = super.getErrorAttributes(request,

isIncludeStackTrace(request, MediaType.ALL));

String message = body.get("message") != null ? (String) body.get("message") : null;

Integer statusCode = body.get("status") != null ? (Integer) body.get("status") : null;

Object exception = body.get("exception");

if (exception instanceof TradeBizException) {

TradeBizException bre = (TradeBizException) exception;

statusCode = bre.getCode();

}

Wrapper wrap = WrapMapper.wrap(statusCode == 0 ? Wrapper.ERROR_CODE : statusCode, message);

Map res = null;

try {

ObjectMapper mapper = new ObjectMapper();

String s = mapper.writeValueAsString(wrap);

res = mapper.readValue(s, Map.class);

} catch (IOException e) {

e.printStackTrace();

}

HttpStatus status = super.getStatus(request);

return new ResponseEntity>(res, status);

}

}

复制代码

参考文章

b739ec46bb5c46d9c0aa4ce35ba1ea56.png

关于找一找教程网

本站文章仅代表作者观点,不代表本站立场,所有文章非营利性免费分享。

本站提供了软件编程、网站开发技术、服务器运维、人工智能等等IT技术文章,希望广大程序员努力学习,让我们用科技改变世界。

[Spring Boot 统一异常管理]http://www.zyiz.net/tech/detail-112787.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值