[英]Java - Throwable to Exception
I am currently using the play2 framework.我目前正在使用 play2 框架。
I have several classes which are throwing exceptions
but play2s global onError
handler uses throwable instead of an exception.我有几个抛出
exceptions
的类,但 play2s 全局onError
处理程序使用 throwable 而不是异常。
for example one of my classes is throwing a NoSessionException
.例如,我的一门课程正在抛出
NoSessionException
。 Can I check a throwable object if it is a NoSessionException
?如果它是
NoSessionException
,我可以检查可抛出对象吗?
You can use instanceof
to check it is of NoSessionException
or not.您可以使用
instanceof
来检查它是否属于NoSessionException
。
Example:例子:
if (exp instanceof NoSessionException) {
...
}
Assuming exp
is the Throwable
reference.假设
exp
是Throwable
引用。
Can I check a throwable object if it is a NoSessionException ?
如果它是 NoSessionException ,我可以检查可抛出对象吗?
Sure:当然:
Throwable t = ...;
if (t instanceof NoSessionException) {
...
// If you need to use information in the exception
// you can cast it in here
}
In addition to checking if its an instanceof
you can use the try catch and catch NoSessionException除了检查它是否为
instanceof
之外,您还可以使用 try catch 和 catch NoSessionException
try {
// Something that throws a throwable
} catch (NoSessionException e) {
// Its a NoSessionException
} catch (Throwable t) {
// catch all other Throwables
}
If you are using Spring, then why not go for a specific exception handler for specific type.如果您使用的是 Spring,那么为什么不使用特定类型的特定异常处理程序。
You can have one GlobalException handler and tag it to your controller您可以拥有一个 GlobalException 处理程序并将其标记到您的控制器
@ControllerAdvice(assignableTypes = {YourController.class})
public class MyGlobalExceptionHandler {
Then you can have specific handler methods to handle specific exception.然后你可以有特定的处理程序方法来处理特定的异常。
for eg below is handling specific ServerWebInputException例如,下面正在处理特定的 ServerWebInputException
@ExceptionHandler(ServerWebInputException.class)
public ResponseEntity<YourResponseObject> handleValidationError(final ServerWebInputException badRequest) {
}
and you can have a generic Throwable handler你可以有一个通用的Throwable 处理程序
@ExceptionHandler(Throwable.class)
public ResponseEntity<YourResponseObject> handleThrowable(final Throwable throwable) {
This would be a clean solution.这将是一个干净的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.