简体   繁体   English

Java - 可抛出异常

[英]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 ,我可以检查可抛出对象吗?

Just make it short.只是让它简短。 We can pass Throwable to Exception constructor.我们可以将Throwable传递给Exception构造函数。

 @Override
 public void onError(Throwable e) {
    Exception ex = new Exception(e);
 }               

See this Exception from Android从 Android 中查看此异常

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.假设expThrowable引用。

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
}

Throwable is a class which Exception – and consequently all subclasses thereof – subclasses. Throwable是一个类,它是Exception - 以及它的所有子类 - 子类。 There's nothing stopping you from using instanceof on a Throwable .没有什么能阻止您在Throwable上使用instanceof

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM