在Spring Boot中如何实现异常处理?
温馨提示:这篇文章已超过385天没有更新,请注意相关的内容是否还可用!
在Spring Boot中,异常处理可以通过几种方式实现,以提高应用程序的健壮性和用户体验。这些方法包括使用@ControllerAdvice注解、@ExceptionHandler注解、实现ErrorController接口等。下面是一些实现Spring Boot异常处理的常用方法:
(图片来源网络,侵删)
1. 使用@ControllerAdvice和@ExceptionHandler
@ControllerAdvice是一个用于全局异常处理的注解,它允许你在整个应用程序中处理异常,而不需要在每个@Controller中重复相同的异常处理代码。@ExceptionHandler用于定义具体的异常处理方法。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public ResponseEntity handleGeneralException(Exception ex, WebRequest request) {
Map body = new LinkedHashMap();
body.put("timestamp", LocalDateTime.now());
body.put("message", "An error occurred");
return new ResponseEntity(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(value = CustomException.class)
public ResponseEntity handleCustomException(CustomException ex, WebRequest request) {
Map body = new LinkedHashMap();
body.put("timestamp", LocalDateTime.now());
body.put("message", ex.getMessage());
return new ResponseEntity(body, HttpStatus.BAD_REQUEST);
}
}
2. 实现ErrorController接口
如果你想自定义/error路径下的错误页面或响应,可以通过实现Spring Boot的ErrorController接口来实现。
@Controller
public class CustomErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError(HttpServletRequest request) {
// 可以获取错误状态码和做其他逻辑处理
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
if (status != null) {
int statusCode = Integer.parseInt(status.toString());
// 根据状态码返回不同的视图名或模型
}
return "errorPage"; // 返回错误页面的视图名
}
@Override
public String getErrorPath() {
return "/error";
}
}
3. ResponseEntityExceptionHandler扩展
通过扩展ResponseEntityExceptionHandler类,你可以覆盖其中的方法来自定义处理特定的异常。这个类提供了一系列方法来处理Spring MVC抛出的常见异常。
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
Map body = new LinkedHashMap();
body.put("timestamp", LocalDateTime.now());
body.put("status", status.value());
List errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(x -> x.getDefaultMessage())
.collect(Collectors.toList());
body.put("errors", errors);
return new ResponseEntity(body, HttpStatus.BAD_REQUEST);
}
// 其他异常处理...
}
通过这些方法,Spring Boot允许开发者灵活地处理应用程序中的异常,无论是全局处理还是特定异常的定制化处理,都能以优雅和统一的方式进行。
免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们,邮箱:ciyunidc@ciyunshuju.com。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!
