线程未捕获异常处理器Thread.UncaughtExceptionHandler

public class Test1 {
    /**
     * 线程未捕获异常处理器接口 Thread.UncaughtExceptionHandler
     * 此接口会在线程由于未捕获异常而突然终止时被调用
     */
    public static class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{

        private String name;

        public CustomUncaughtExceptionHandler(String name) {
            this.name = name;
        }

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            System.out.println(t.getName()+" 发生异常,终止了");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {

        /**
         * 设置默认未捕获异常处理器
         */
        Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler("自定义未捕获异常处理器"));

        new Thread(new Runnable() {
            /**
             * Runnable接口中的run方法没有抛出受检查异常,实现类的run方法也就只能抛出不受检查的异常RuntimeException
             */
            @Override
            public void run() {
                throw new RuntimeException();
            }
        }, "线程-1").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException();
            }
        }, "线程-2").start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                throw new RuntimeException();
            }
        }, "线程-3").start();
    }

}

在spring-boot工程中配置全局异常处理器

@ControllerAdvice
public class LearnControllerAdvice {

    final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    /**
     * 全局异常处理器
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> errorHandler(Exception ex) {
        LOGGER.error("发生异常", ex);
        // 请求报错,status设置为0
        int status = 0;
        String message = "";
        if (ex instanceof CustomException) {
            status = ((CustomException) ex).getCode();
            message = ex.getMessage();
        }else if (ex instanceof NullPointerException) {
            message = "空指针异常";
        }else {
            message = "服务暂不可用";
        }
        Map<String, Object> result = new HashMap<>();
        result.put("status", status);
        result.put("message", message);
        return result;
    }

}
发布了51 篇原创文章 · 获赞 14 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/u010606397/article/details/103905370