springboot全局自定义异常

简介: springboot全局自定义异常

1.自定义异常

package com.xxx.dzwz.util.exception;

/**

  • 自定义异常
  • @date 2024-01-19 10:00:00
  • @author wangwei
    */
    public class CustomException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    private Integer code;

    private String message;

    public CustomException(String message) {
    this.message = message;
    }

    public CustomException(String message, Integer code) {
    this.message = message;
    this.code = code;
    }

    public CustomException(String message, Throwable e) {
    super(message, e);
    this.message = message;
    }

    @Override
    public String getMessage() {
    return message;
    }

    public Integer getCode() {
    return code;
    }

}
2.业务异常
package com.xxx.dzwz.util.exception;

/**

  • 业务异常
  • @author wangwei
    */
    public final class ServiceException extends RuntimeException
    {
    private static final long serialVersionUID = 1L;

    /**

    • 错误码
      */
      private Integer code;

      /**

    • 错误提示
      */
      private String message;

      /**

    • 错误明细,内部调试错误
      *
    • 和 {@link CommonResult#getDetailMessage()} 一致的设计
      */
      private String detailMessage;

      /**

    • 空构造方法,避免反序列化问题
      */
      public ServiceException()
      {
      }

      public ServiceException(String message)
      {
      this.message = message;
      }

      public ServiceException(String message, Integer code)
      {
      this.message = message;
      this.code = code;
      }

      public String getDetailMessage()
      {
      return detailMessage;
      }

      @Override
      public String getMessage()
      {
      return message;
      }

      public Integer getCode()
      {
      return code;
      }

      public com.cmrx.dzwz.util.exception.ServiceException setMessage(String message)
      {
      this.message = message;
      return this;
      }

      public com.cmrx.dzwz.util.exception.ServiceException setDetailMessage(String detailMessage)
      {
      this.detailMessage = detailMessage;
      return this;
      }
      }

3.全局异常处理器
package com.xxx.dzwz.util.exception;
import com.xxx.dzwz.util.AjaxResult;
import com.xxx.dzwz.util.StringUtils;
import com.xxx.dzwz.util.pageutil.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.nio.file.AccessDeniedException;

/**

  • 全局异常处理器
    • @date 2024-01-30 09:46:00
  • @author wangwei
    */
    @RestControllerAdvice
    public class GlobalExceptionHandler
    {
    private static final Logger log = LoggerFactory.getLogger(com.cmrx.dzwz.util.exception.GlobalExceptionHandler.class);

    /**

    • 权限校验异常
      */
      @ExceptionHandler(AccessDeniedException.class)
      public AjaxResult handleAccessDeniedException(AccessDeniedException e, HttpServletRequest request)
      {
      String requestURI = request.getRequestURI();
      log.error("请求地址'{}',权限校验失败'{}'", requestURI, e.getMessage());
      return AjaxResult.error(HttpStatus.FORBIDDEN, "没有权限,请联系管理员授权");
      }

      /**

    • 请求方式不支持
      */
      @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
      public AjaxResult handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,

                                                     HttpServletRequest request)
      

      {
      String requestURI = request.getRequestURI();
      log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
      return AjaxResult.error(e.getMessage());
      }

      /**

    • 业务异常
      */
      @ExceptionHandler(ServiceException.class)
      public AjaxResult handleServiceException(ServiceException e, HttpServletRequest request)
      {
      log.error(e.getMessage(), e);
      Integer code = e.getCode();
      return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());
      }

      /**

    • 拦截未知的运行时异常
      */
      @ExceptionHandler(RuntimeException.class)
      public AjaxResult handleRuntimeException(RuntimeException e, HttpServletRequest request)
      {
      String requestURI = request.getRequestURI();
      log.error("请求地址'{}',发生未知异常.", requestURI, e);
      return AjaxResult.error(e.getMessage());
      }

      /**

    • 系统异常
      */
      @ExceptionHandler(Exception.class)
      public AjaxResult handleException(Exception e, HttpServletRequest request)
      {
      String requestURI = request.getRequestURI();
      log.error("请求地址'{}',发生系统异常.", requestURI, e);
      return AjaxResult.error(e.getMessage());
      }

      /**

    • 自定义验证异常
      */
      @ExceptionHandler(BindException.class)
      public AjaxResult handleBindException(BindException e)
      {
      log.error(e.getMessage(), e);
      String message = e.getAllErrors().get(0).getDefaultMessage();
      return AjaxResult.error(message);
      }

      /**

    • 自定义验证异常
      */
      @ExceptionHandler(MethodArgumentNotValidException.class)
      public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException e)
      {
      log.error(e.getMessage(), e);
      String message = e.getBindingResult().getFieldError().getDefaultMessage();
      return AjaxResult.error(message);
      }

      /**

    • 演示模式异常
      /
      /
      @ExceptionHandler(DemoModeException.class)
      public AjaxResult handleDemoModeException(DemoModeException e)
      {
      return AjaxResult.error("演示模式,不允许操作");
      }*/
      }
相关文章
|
5月前
|
JSON 前端开发 Java
解决Spring MVC中No converter found for return value of type异常
在Spring MVC开发中遇到`No converter found for return value of type`异常,通常是因缺少消息转换器、返回值类型不支持或转换器优先级配置错误。解决方案包括:1) 添加对应的消息转换器,如`MappingJackson2HttpMessageConverter`;2) 自定义消息转换器并实现`HttpMessageConverter`接口,设置优先级;3) 修改返回值类型为如`ResponseEntity`的合适类型。通过这些方法可确保返回值正确转换为响应内容。
345 1
|
2月前
|
前端开发 小程序 Java
【规范】SpringBoot接口返回结果及异常统一处理,这样封装才优雅
本文详细介绍了如何在SpringBoot项目中统一处理接口返回结果及全局异常。首先,通过封装`ResponseResult`类,实现了接口返回结果的规范化,包括状态码、状态信息、返回信息和数据等字段,提供了多种成功和失败的返回方法。其次,利用`@RestControllerAdvice`和`@ExceptionHandler`注解配置全局异常处理,捕获并友好地处理各种异常信息。
237 0
【规范】SpringBoot接口返回结果及异常统一处理,这样封装才优雅
|
2月前
|
消息中间件 Java 开发工具
【Azure 事件中心】Spring Cloud Stream Event Hubs Binder 发送Event Hub消息遇见 Spec. Rule 1.3 - onSubscribe, onNext, onError and onComplete signaled to a Subscriber MUST be signaled serially 异常
【Azure 事件中心】Spring Cloud Stream Event Hubs Binder 发送Event Hub消息遇见 Spec. Rule 1.3 - onSubscribe, onNext, onError and onComplete signaled to a Subscriber MUST be signaled serially 异常
|
2月前
|
Java Spring
【Azure 事件中心】Spring Boot 集成 Event Hub(azure-spring-cloud-stream-binder-eventhubs)指定Partition Key有异常消息
【Azure 事件中心】Spring Boot 集成 Event Hub(azure-spring-cloud-stream-binder-eventhubs)指定Partition Key有异常消息
|
2月前
|
Java Spring
【Azure 服务总线】Spring Cloud 的应用 使用Service Bus 引起 org.springframework.beans.BeanInstantiationException 异常,无法启动
【Azure 服务总线】Spring Cloud 的应用 使用Service Bus 引起 org.springframework.beans.BeanInstantiationException 异常,无法启动
|
2月前
|
NoSQL Java Redis
【Azure Spring Cloud】Java Spring Cloud 应用部署到Azure上后,发现大量的 java.lang.NullPointerException: null at io.lettuce.core.protocol.CommandHandler.writeSingleCommand(CommandHandler.java:426) at ... 异常
【Azure Spring Cloud】Java Spring Cloud 应用部署到Azure上后,发现大量的 java.lang.NullPointerException: null at io.lettuce.core.protocol.CommandHandler.writeSingleCommand(CommandHandler.java:426) at ... 异常
|
2月前
|
Dubbo Java Nacos
【实战攻略】破解Dubbo+Nacos+Spring Boot 3 Native打包后运行异常的终极秘籍——从零开始彻底攻克那些让你头疼不已的技术难题!
【8月更文挑战第15天】Nacos作为微服务注册与配置中心受到欢迎,但使用Dubbo+Nacos+Spring Boot 3进行GraalVM native打包后常遇运行异常。本文剖析此问题及其解决策略:确认GraalVM版本兼容性;配置反射列表以支持必要类和方法;采用静态代理替代动态代理;检查并调整配置文件;禁用不支持的功能;利用日志和GraalVM诊断工具定位问题;根据诊断结果调整GraalVM配置。通过系统排查方法,能有效解决此类问题,确保服务稳定运行。
68 0
|
3月前
|
Java Spring 容器
Spring循环依赖问题之两个不同的Bean A,导致抛出异常如何解决
Spring循环依赖问题之两个不同的Bean A,导致抛出异常如何解决
|
3月前
|
存储 缓存 Java
Spring循环依赖问题之循环依赖异常如何解决
Spring循环依赖问题之循环依赖异常如何解决
|
3月前
|
XML Java 数据格式
循环依赖问题之创建Bean的过程中发生异常,Spring会如何处理
循环依赖问题之创建Bean的过程中发生异常,Spring会如何处理
下一篇
无影云桌面