1.创建异常属性类继承RunTimeException
package com.atguigu.servicebase.exceptionHandler; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class GuliException extends RuntimeException{ private Integer code; private String msg; } 图文:
2.创建异常类
package com.atguigu.servicebase.exceptionHandler; import com.atguigu.commonutils.R; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; //全局异常 @ControllerAdvice public class GlobalExceptionHandler { @ResponseBody @ExceptionHandler(Exception.class) public R error(Exception e){ e.printStackTrace(); return R.error().message("出了点问题,请稍后再试"); } //特定异常(这里是空指针异常) @ResponseBody @ExceptionHandler(NullPointerException.class) public R error(NullPointerException e){ e.printStackTrace(); return R.error().message("出了点问题,请稍后再试"); } //自定义异常 @ResponseBody @ExceptionHandler(GuliException.class) public R error(GuliException e){ e.printStackTrace(); return R.error().code(e.getCode()).message(e.getMsg()); } } 图文:
流程图: