全局异常捕获的使用:
Spring的@ExceptionHandler注解使用方法
其他问题:
引用的文章说:
SQLException 和 IOException 这两个家伙的 e.getMessage() 不为空。
RuntimeException 里面的异常,
ArrayIndexOutOfBoundsException,
NullPointerException,
ClassCastException,
ArithmeticException
这些家伙, e.getMessage() 都是 null 。
实践:
环境:JDK1.8
我自己实践了 ArithmeticException异常 和 ArrayIndexOutOfBoundsException异常 的代码分析, 与博主说的不一样:e.getMessage 均不为 null
ArithmeticException异常:
ArrayIndexOutOfBoundsException异常:
疑问: 这不禁让我陷入思考,我引用文章中那位博主说的问题e.getMessage() = null 是怎么出现的?希望评论区大佬们帮忙解答,谢谢。
________________________________________________________________________________________________________
说一下我遇到的问题场景:即 我为什么会关注到 e.getMessage() 为 null 这个问题:
我通过自定义异常类对异常进行处理
1.捕获并抛出异常
2.构造器
3.自定义异常捕获机制
我遇到的问题就出现在这里,我返回给前端的错误信息为 null ,即 e.getMessage() = null
4.解决办法:
构造器里的方法 super(message) 改成 this.message = message;
5.将错就错,顺便看了下异常父类的构造方法
可以看到不断在走父级的构造方法,到最后
super() —> RuntimeException() —> Exception() —> Throwable()
(1)
(2)
(3)
(4)
可以看到,异常对象 e 的 detailMessage 的属性值赋值给了 message
即 throw new Exception(“自定义信息”) 后,在异常捕获类中,返回给客户端的信息就是我们自定义的信息
return new MercuryResponseDTO().code(HttpStatus.INTERNAL_SERVER_ERROR).message(e.getMessage());