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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端可以通过后端返回的 HTTP 状态码以及返回的错误信息来获得后端抛出的异常。在 Spring MVC/Boot 中,可以通过统一异常处理来捕获和处理后端的异常。 最佳实践是,定义一个全局异常处理器,通过 @ControllerAdvice 和 @ExceptionHandler 注解来统一处理异常。在全局异常处理器中,可以捕获所有的异常,并根据不同的异常类型进行不同的处理,例如返回不同的 HTTP 状态码和错误信息。 下面是一个简单的示例代码: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) @ResponseBody public ResponseEntity<Object> handleException(Exception ex) { HttpStatus status = getStatus(ex); ErrorResponse errorResponse = new ErrorResponse(status.value(), ex.getMessage()); return new ResponseEntity<>(errorResponse, status); } private HttpStatus getStatus(Exception ex) { if (ex instanceof BadRequestException) { return HttpStatus.BAD_REQUEST; } else if (ex instanceof NotFoundException) { return HttpStatus.NOT_FOUND; } else { return HttpStatus.INTERNAL_SERVER_ERROR; } } } ``` 在上面的代码中,handleException 方法可以捕获所有的异常,并根据异常类型返回不同的 HTTP 状态码和错误信息。例如,如果是 BadRequestException 异常,就返回 400 Bad Request 状态码;如果是 NotFoundException 异常,就返回 404 Not Found 状态码;否则返回 500 Internal Server Error 状态码。同时,也可以在异常处理器中记录日志等信息,以便后续排查问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值