找回密码
 立即注册
查看: 3|回复: 0

18,全局异常处理类,自定义异常处理类

[复制链接]

215

主题

6

精华

219

金币

技术维护QQ:515138

积分
468
发表于 昨天 20:39 | 显示全部楼层 |阅读模式
全局异常处理类:

  1. package com.jinhei.exception;
  2. import com.jinhei.pojp.Result;
  3. import org.springframework.util.StringUtils;
  4. import org.springframework.web.bind.annotation.ExceptionHandler;
  5. import org.springframework.web.bind.annotation.RestControllerAdvice;
  6. /**
  7. * 全局异常处理类
  8. */
  9. @RestControllerAdvice
  10. public class GlobalExceptionHandler {
  11.    
  12.     //处理异常
  13.     @ExceptionHandler(Exception.class)
  14.     public Result handleException(Exception e){//方法形参中指定能够处理的异常类型
  15.         e.printStackTrace();//打印堆栈中的异常信息
  16.         //捕获到异常之后,响应一个标准的Result
  17.         return Result.error(StringUtils.hasLength(e.getMessage()) ? e.getMessage() : "操作失败");
  18. //        return Result.error("对不起,操作失败,请联系管理员");
  19.     }
  20.    
  21. }
复制代码
另外一个示例:
  1. package com.zidiu.exception;
  2. import com.zidiu.pojo.Result;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.dao.DuplicateKeyException;
  5. import org.springframework.web.bind.annotation.ExceptionHandler;
  6. import org.springframework.web.bind.annotation.RestControllerAdvice;
  7. /**
  8. * 全局异常处理器
  9. */
  10. @Slf4j
  11. @RestControllerAdvice
  12. public class GlobalExceptionHandler {
  13.     @ExceptionHandler
  14.     public Result handleException(Exception e){
  15.         log.error("程序出错啦~", e);
  16.         return Result.error("出错啦, 请联系管理员~");
  17.     }
  18.     @ExceptionHandler
  19.     public Result handleDuplicateKeyException(DuplicateKeyException e){
  20.         log.error("程序出错啦~", e);
  21.         String message = e.getMessage();
  22.         int i = message.indexOf("Duplicate entry");
  23.         String errMsg = message.substring(i);
  24.         String[] arr = errMsg.split(" ");
  25.         return Result.error( arr[2] + " 已存在");
  26.     }
  27. }
复制代码
以上就是全局异常处理器的使用,主要涉及到两个注解:
  • @RestControllerAdvice  //表示当前类为全局异常处理器
  • @ExceptionHandler  //指定可以捕获哪种类型的异常进行处理

网站建设,公众号小程序开发,系统定制,软件App开发,技术维护【联系我们】手机/微信:17817817816 QQ:515138

QQ|Archiver|自丢网 ( 粤ICP备2024252464号-1 )

GMT+8, 2026-2-27 07:30

专注于网站建设,公众号小程序制作,商城小程序,系统定制,软件App开发

【联系我们】手机/微信:17817817816 QQ:515138

快速回复 返回顶部 返回列表