当前位置:   article > 正文

线程未捕获异常处理器Thread.UncaughtExceptionHandler_thread.uncaughtexceptionhandler sneakythrows

thread.uncaughtexceptionhandler sneakythrows
  1. public class Test1 {
  2. /**
  3. * 线程未捕获异常处理器接口 Thread.UncaughtExceptionHandler
  4. * 此接口会在线程由于未捕获异常而突然终止时被调用
  5. */
  6. public static class CustomUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler{
  7. private String name;
  8. public CustomUncaughtExceptionHandler(String name) {
  9. this.name = name;
  10. }
  11. @Override
  12. public void uncaughtException(Thread t, Throwable e) {
  13. System.out.println(t.getName()+" 发生异常,终止了");
  14. e.printStackTrace();
  15. }
  16. }
  17. public static void main(String[] args) {
  18. /**
  19. * 设置默认未捕获异常处理器
  20. */
  21. Thread.setDefaultUncaughtExceptionHandler(new CustomUncaughtExceptionHandler("自定义未捕获异常处理器"));
  22. new Thread(new Runnable() {
  23. /**
  24. * Runnable接口中的run方法没有抛出受检查异常,实现类的run方法也就只能抛出不受检查的异常RuntimeException
  25. */
  26. @Override
  27. public void run() {
  28. throw new RuntimeException();
  29. }
  30. }, "线程-1").start();
  31. new Thread(new Runnable() {
  32. @Override
  33. public void run() {
  34. throw new RuntimeException();
  35. }
  36. }, "线程-2").start();
  37. new Thread(new Runnable() {
  38. @Override
  39. public void run() {
  40. throw new RuntimeException();
  41. }
  42. }, "线程-3").start();
  43. }
  44. }

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

  1. @ControllerAdvice
  2. public class LearnControllerAdvice {
  3. final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
  4. /**
  5. * 全局异常处理器
  6. */
  7. @ExceptionHandler(Exception.class)
  8. @ResponseBody
  9. public Map<String, Object> errorHandler(Exception ex) {
  10. LOGGER.error("发生异常", ex);
  11. // 请求报错,status设置为0
  12. int status = 0;
  13. String message = "";
  14. if (ex instanceof CustomException) {
  15. status = ((CustomException) ex).getCode();
  16. message = ex.getMessage();
  17. }else if (ex instanceof NullPointerException) {
  18. message = "空指针异常";
  19. }else {
  20. message = "服务暂不可用";
  21. }
  22. Map<String, Object> result = new HashMap<>();
  23. result.put("status", status);
  24. result.put("message", message);
  25. return result;
  26. }
  27. }

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/250827
推荐阅读
相关标签
  

闽ICP备14008679号