SpringBoot项目异常的统一处理

朴灿烈づ我的快乐病毒、 2023-10-04 08:58 25阅读 0赞

采用Spring提供了一个通用的异常处理器ControllerAdvice,可以非常方便的帮助我们实现统一的异常处理。

1.定义异常处理器

ControllerExceptionAdvice

  1. package com.ats.dt.advice;
  2. import com.ats.dt.exceptions.HandleException;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.http.MediaType;
  5. import org.springframework.http.ResponseEntity;
  6. import org.springframework.web.bind.annotation.ControllerAdvice;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. /**
  9. * 要让这个类生效,必须让项目可以扫描到这个类所在的包,将其加入Spring容器。启动类的注解上添加扫描包信息
  10. */
  11. @ControllerAdvice //会拦截所有加了@Controller的类,相当于给所有的controller写了一个try
  12. @Slf4j
  13. public class ControllerExceptionAdvice {
  14. /**
  15. * 统一异常处理方法,@ExceptionHandler(HandleException.class)声明这个方法处理RuntimeException这样的异常
  16. * @param e 捕获到的异常
  17. * @return 返回给页面的状态码和信息
  18. */
  19. @ExceptionHandler(HandleException.class) //相当于catch
  20. public ResponseEntity<String> handleProjectException(HandleException e) {
  21. return ResponseEntity
  22. .status(e.getStatus())
  23. .contentType(MediaType.APPLICATION_JSON)
  24. .body(e.getMessage());
  25. }
  26. }

代码解读:

  • @ControllerAdvice:添加了@ControllerAdvice的类,默认情况下,会拦截所有加了@Controller的类
  • @ExceptionHandler(HandleException.class):作用在方法上,声明要处理的异常类型,这里指定的是HandleException。因此任意Controller抛出HandleException都会被当前方法捕获和处理

    • 参数:捕获到的异常
    • 返回值:给页面的提示信息。这里返回值中不仅给出了状态码400,还给出了异常的message

2.自定义异常

  1. package com.ats.dt.exceptions;
  2. import lombok.Getter;
  3. import lombok.extern.slf4j.Slf4j;
  4. @Slf4j
  5. @Getter
  6. public class HandleException extends RuntimeException {
  7. /**
  8. * 异常状态码信息
  9. */
  10. private Integer status;
  11. public HandleException(int status) {
  12. this.status = status;
  13. }
  14. public HandleException(int status, String message) {
  15. super(message);
  16. this.status = status;
  17. }
  18. /**
  19. * cause清楚的定位到是哪里的错(异常的起源)
  20. * @param status 状态码
  21. * @param message 消息内容
  22. * @param cause 异常起源
  23. */
  24. public HandleException(int status, String message, Throwable cause) {
  25. super(message, cause);
  26. this.status = status;
  27. }
  28. public HandleException(int status, Throwable cause) {
  29. super(cause);
  30. this.status = status;
  31. }
  32. }

3.使用自定义异常

3.1 实体类

  1. @Data
  2. public class Item {
  3. private Integer id;
  4. private String name;
  5. private Long price;
  6. }

3.2controller层

  1. package com.ats.dt.controller;
  2. import com.ats.dt.service.impl.ItemService;
  3. import com.ats.dt.vo.Item;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.*;
  8. @RestController
  9. @RequestMapping(value = "item")
  10. @CrossOrigin
  11. public class ItemController {
  12. @Autowired
  13. private ItemService itemService;
  14. @PostMapping(value = "test")
  15. @ResponseBody
  16. public ResponseEntity<Item> saveItem(Item item) {
  17. Item result = itemService.saveItem(item);
  18. // 新增成功, 返回201
  19. return ResponseEntity.status(HttpStatus.CREATED).body(result);
  20. }
  21. }

3.3 service层业务实现

  1. package com.ats.dt.service.impl;
  2. import com.ats.dt.exceptions.HandleException;
  3. import com.ats.dt.vo.Item;
  4. import org.springframework.stereotype.Service;
  5. import java.util.Random;
  6. @Service
  7. public class ItemService {
  8. public Item saveItem(Item item){
  9. // 判断价格是否为空
  10. if(item.getPrice() == null){
  11. throw new HandleException(401,"价格不能为空");
  12. }
  13. if(item.getName() == null){
  14. throw new HandleException(400,"名称不能为空");
  15. }
  16. // 随机生成id,模拟数据库的新增
  17. int id = new Random().nextInt(100);
  18. item.setId(id);
  19. // 返回新增之后的对象,回显id
  20. return item;
  21. }
  22. }

4.测试结果

制造异常,将价格设置空
在这里插入图片描述

5.注意

确保springBoot启动时能使异常处理器能够加载到

6、日志的统一处理

日志统一处理

发表评论

表情:
评论列表 (有 0 条评论,25人围观)

还没有评论,来说两句吧...

相关阅读