封装自定义异常(代码片段)

wenwblog wenwblog     2022-12-24     350

关键词:

  • 才开通博客没几天,不知道写什么东西,就把最近在项目中做的东西分享一下,开通博客也可以监督一下自己,技术的路很遥远,希望能通过写博客来让自己走的更远。

  • 一般在web项目中都需要定义一个全局异常来处理一些业务方面的异常,下面是自定义异常的一些代码。

1.自定义一个异常,然后继承RuntimeException

/**
 * @author zhuwenwen
 * @date 2018/8/16 20:18
 */
@Getter
public class CustomException extends RuntimeException 
    /**
     * 异常编码
     */
    private Integer code;

    /**
     * 附加数据
     */
    private Object data;

    public CustomException(String errorMsg) 

        super(errorMsg);
        this.code= CustomEnum.ERROR.getCode();
    

    public CustomException(String errorMsg, Integer code) 
        super(errorMsg);
        this.code = code;
    

    public CustomException(Integer code, String errorMsg, Throwable errorCourse) 
        super(errorMsg,errorCourse);
        this.code = code;
    

    public CustomException(String message, Integer code, Object data) 
        super(message);
        this.code = code;
        this.data = data;
    


2.定义一个全局异常处理的类

/**
 * 处理全局异常
 *
 * @author zhuwenwen
 * @date 2018/8/17 9:31
 */
@RestControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler implements CustomExceptionHanlerTrit 


    private Logger logger=LoggerFactory.getLogger(CustomExceptionHandler.class);
    /**
     *
     * @see ResponseEntityExceptionHandler#handleExceptionInternal
     */
    @Override
    protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status,WebRequest webRequest) 
        logger.warn("", ex.getMessage());

        return handleException(CustomEnum.FAILURE_HTTP.getCode() + status.value(), ex.getMessage(), null);
    

    /**
     * 处理ServletException
     *
     * @param ex      异常
     * @return        异常处理结果
     */
    @ExceptionHandler(value = ServletException.class)
    protected final ResponseEntity<Object> handleServletException(ServletException ex) 
        logger.error("", ex);

        return handleException(CustomEnum.FAILURE_SERVLET.getCode(), ex.getMessage(), null);
    

    /**
     * 处理SQLException
     *
     * @param ex      异常
     * @return        异常处理结果
     */
    @ExceptionHandler(value = SQLException.class)
    protected final ResponseEntity<Object> handleSQLException(SQLException ex) 
        logger.error("", ex);

        return handleException(CustomEnum.FAILURE_DB.getCode(), ex.getMessage(), null);
    

    /**
     * 处理ConstraintViolationException
     *
     * @param ex      异常
     * @return        异常处理结果
     */
    @ExceptionHandler(value = ConstraintViolationException.class)
    protected final ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException ex) 
        logger.error("", ex);

        String message = ex.getMessage();
        if (ex.getConstraintViolations() != null && !ex.getConstraintViolations().isEmpty()) 
            message = ex.getConstraintViolations().stream().findFirst().isPresent()
                    ? ex.getConstraintViolations().stream().findFirst().get().getMessage() : null;
        

        return handleException(CustomEnum.FAILURE_VALIDATION.getCode(), message, null);
    

    /**
     * 处理MorphedException
     *
     * @param ex      异常
     * @return        异常处理结果
     */
    @ExceptionHandler(value = CustomException.class)
    protected final ResponseEntity<Object> handleMorphedException(CustomException ex) 
        logger.info("", ex);

        return handleException(ex.getCode(), ex.getMessage(),ex.getData());
    

    /**
     * 处理RuntimeException
     *
     * @param ex      异常
     * @return        异常处理结果
     */
    @ExceptionHandler(value = RuntimeException.class)
    protected final ResponseEntity<Object> handleRuntimeException(RuntimeException ex) 
        logger.error("", ex);

        return handleException(CustomEnum.FAILURE_UNKNOWN.getCode(), ex.getMessage(), null);
    

3.封装成一个组件,可以打成jar包,供多个项目使用,那么可以自定义一个注解,然后在启动类上加上这个注解,即可使用。下面是一个简单的demo

/**
 * @author zhuwenwen
 * @date 2018/8/17 11:02
 */

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Import(CustomExceptionHandler.class)
@Documented
public @interface EnableCustomException 
    /**
     * 是否开启
     * @return
     */
    boolean enabled() default true;



/**
 * @author zhuwenwen
 * @date 2018/8/17 14:47
 */
public class CustomImportBeanDefination implements ImportBeanDefinitionRegistrar 
    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) 
        //是否含有@EnableMorphedException注解
        if (annotationMetadata.isAnnotated(EnableCustomException.class.getName()))
            //获取该注解上面的所有属性,然后封装成一个map
            MultiValueMap<String, Object> attributes = annotationMetadata.getAllAnnotationAttributes(EnableCustomException.class.getName());
            if(attributes.get(EnableCustomExceptionCode.ENABLED).equals(Boolean.TRUE))
                BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(CustomExceptionHandler.class);
                beanDefinitionRegistry.registerBeanDefinition(CustomExceptionHandler.class.getName(),beanDefinitionBuilder.getBeanDefinition());
            
        
    

springcloud请求异常处理封装businessexception自定义异常类(代码片段)

文章目录请求异常处理1异常信息格式2异常处理流程3自定义业务异常类4自定义业务异常处理器5抛出自定义异常请求异常处理1异常信息格式系统在交互中难免会有异常发生,前端为了解析异常信息向用户提示特定义了异常信... 查看详情

自定义runtimeexception工具类(代码片段)

...示传递给前端1.定义一个异常的工具类extendsRuntimeException2.封装统一的响应工具类自定义异常MyInfoException,将异常提示传递给前端1.定义一个异常的工具类extendsRuntimeExceptionpackagecom.monkey;publicclassMyRuntimeExceptionexten 查看详情

laravel->exceptions->apiexception自定义错误异常的封装(代码片段)

...文Laravel->Exceptions->Handler->render错误异常的封装_丿灬安之若死-CSDN博客 <?php/***@Description*@Date2021-12-2105:24*/namespaceModules\\Common\\Exceptions;useException;useThrowable;classApiExceptionextendsExceptionpublicfunction__construct($message&#... 查看详情

自定义封装exception异常抛出

话不多说直接上代码,朋友们可自己测试用于项目:BaseException类(基础类)  /***异常处理基类*/publicclassBaseExceptionextendsRuntimeExceptionprivatestaticfinallongserialVersionUID=-3653870580234213024L;protectedStringmessageKey;publicBas 查看详情

自定义异常(代码片段)

为什么需要自定义异常类我们说了Java中不同的异常类,分别表示着某一种具体的异常情况,那么在开发中总是有些异常情况是SUN没有定义好的,此时我们根据自己业务的异常情况来定义异常类。什么是自定义异常类:在开发中根据自... 查看详情

vscode自定义代码片段14——vue的axios网络请求封装(代码片段)

Vue的axios网络请求封装 //V'axios //14如何自定义用户代码片段:VSCode=》左下角设置=》用户代码片段=》新建全局代码片段文件...=》自定义片段名称=》编辑用户片段=》ctrl+S保存 //Vue的axios网络请求封装 ... 查看详情

vscode自定义代码片段14——vue的axios网络请求封装(代码片段)

Vue的axios网络请求封装 //V'axios //14如何自定义用户代码片段:VSCode=》左下角设置=》用户代码片段=》新建全局代码片段文件...=》自定义片段名称=》编辑用户片段=》ctrl+S保存 //Vue的axios网络请求封装 ... 查看详情

自定义异常(代码片段)

为什么要自定义异常类?Java中不同的异常类,分别表示着某一种具体的异常情况,那么在开发中有些异常情况Java中没有定义好,此时我们根据自己业务的异常情况来定义异常类。异常类如何定义?格式:public classXXXExceptionex... 查看详情

rubyruby自定义异常(代码片段)

查看详情

自定义异常(代码片段)

1packagedemo2;23/**4*自定义异常5*@author6*7*/8publicclassMyExceptionextendsException910publicMyException()11super();121314publicMyException(Stringmessage)15super(message);1617181packagedemo2;23import 查看详情

springsecurity从入门到精通:从数据库查询权限信息&自定义失败处理(代码片段)

...败出现的异常。​  如果是认证过程中出现的异常会被封装成AuthenticationException然后调用AuthenticationEntryPoint对象的方法去进行异常处理。​  如果是授权过程中出现的异常会被封装成AccessDeniedException然后调用AccessDeniedHandler对... 查看详情

python编写自定义异常。(代码片段)

查看详情

rubyruby自定义异常类(代码片段)

查看详情

python自定义异常类(代码片段)

查看详情

自定义异常(代码片段)

定义一个类publicclassAgeOutOfBoundsExceptionextendsException根据父类的构造方法生成一个构造方法一般情况下只要无参和String通过throw抛出一个异常对象throw所在的方法通过throw声明改异常在调用方法的时候捕获处理 查看详情

自定义异常(代码片段)

自定义异常自定义异常概述当java里面的异常无法满足开发者的需求时,可以自定义异常。packagecom.monkey1024.exception;publicclassUserService//注册的方法publicvoidregister(Stringname)if(name.length()<6)//需要在这里面一个抛出非法注册名的异常,... 查看详情

自定义异常(代码片段)

自定义异常在程序运行的时候,有的时候执行完一段代码的时候你发现程序代码不符合逻辑,所以我们想要return结束这段代码,但是这段代码所在的方法的返回值类型又是void,因此我们没办法return,所以这个... 查看详情

自定义异常(代码片段)

自定义异常在程序运行的时候,有的时候执行完一段代码的时候你发现程序代码不符合逻辑,所以我们想要return结束这段代码,但是这段代码所在的方法的返回值类型又是void,因此我们没办法return,所以这个... 查看详情