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