当前位置: 首页 > news >正文

在Spring Boot中如何实现异常处理?

在Spring Boot中,异常处理可以通过几种方式实现,以提高应用程序的健壮性和用户体验。这些方法包括使用@ControllerAdvice注解、@ExceptionHandler注解、实现ErrorController接口等。下面是一些实现Spring Boot异常处理的常用方法:

1. 使用@ControllerAdvice@ExceptionHandler

@ControllerAdvice是一个用于全局异常处理的注解,它允许你在整个应用程序中处理异常,而不需要在每个@Controller中重复相同的异常处理代码。@ExceptionHandler用于定义具体的异常处理方法。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<Object> handleGeneralException(Exception ex, WebRequest request) {
        Map<String, Object> 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<Object> handleCustomException(CustomException ex, WebRequest request) {
        Map<String, Object> 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<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("timestamp", LocalDateTime.now());
        body.put("status", status.value());
        List<String> 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允许开发者灵活地处理应用程序中的异常,无论是全局处理还是特定异常的定制化处理,都能以优雅和统一的方式进行。

相关文章:

  • 云计算 2月28号 (linux的磁盘分区)
  • LeetCode-第14题-最长公共前缀
  • nextjs13如何进行服务端渲染?
  • wordpress 开源主题
  • k8s学习-数据管理之nfs手动搭建
  • 基于JavaWEB SpringBoot婚纱影楼摄影预约网站设计和实现
  • Timeplus-proton流处理器调研
  • 自动驾驶加速落地,激光雷达放量可期(上)
  • 突破编程_C++_STL教程( list 的实战应用)
  • C语言基础(五)——结构体与C++引用
  • C/C++嵌入式开发环境搭建,Qt交叉编译,cmake交叉编译,clion/vscode远程开发
  • Qt 简约美观的加载动画 小沙漏风格 第六季
  • C语言:结构体(自定义类型)知识点(包括结构体内存对齐的热门知识点)
  • Spring Boot 常用注解大全
  • 【数据结构与算法】常见排序算法(Sorting Algorithm)
  • leetcode热题100学习计划-链表-反转链表
  • 对象变更记录objectlog工具(持续跟新)
  • Mybatis - generator(自动生成)
  • 蓝桥杯(3.2)
  • 前端vue后端go实现大文件分片下载
  • 航天科技集团质量技术部部长严泽想升任集团副总经理
  • 最大规模的陈逸飞大展启幕:回望他,回望一个时代
  • 30天内三访中国,宝马董事长:没有一家公司可以在全球价值链外独立运行
  • 特朗普签署行政命令推动深海采矿,被指无视国际规则,引发环境担忧
  • 中国铝业首季“开门红”:净利润超35亿元,同比增加近六成
  • 河南省鹤壁市人大常委会副主任李杰接受审查调查