Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java @ExceptionHandler本地vs全局_Java_Spring_Spring Mvc_Exception Handling - Fatal编程技术网

Java @ExceptionHandler本地vs全局

Java @ExceptionHandler本地vs全局,java,spring,spring-mvc,exception-handling,Java,Spring,Spring Mvc,Exception Handling,我将在我的web应用程序上介绍全局处理程序: @ControllerAdvice public class GlobalControllerExceptionHandler { @ExceptionHandler(CustomRuntimeException.class) public @ResponseBody ImmutableMap<?, String> handleNullResponseException(CustomRuntimeException e)

我将在我的web应用程序上介绍全局处理程序

@ControllerAdvice
public class GlobalControllerExceptionHandler {

    @ExceptionHandler(CustomRuntimeException.class)
    public @ResponseBody ImmutableMap<?, String> handleNullResponseException(CustomRuntimeException e) {
        return ImmutableMap.of(e.getClass(), e.getMessage());
    }
}
当控制器抛出CustomRuntimeException时,它由本地异常处理,而不是全局异常处理。为了修复它,我可以向每个控制器添加类似于全局的本地处理程序。但对我来说,这不是个好主意


问题:是否可以将处理自定义异常重定向到全局处理程序?

您需要在本地
异常处理程序
中放置更具体的异常,在全局
异常处理程序
中放置更一般的异常。类似于Java异常处理。如果将常规异常放在本地,则所有异常都将在那里结束,因为它是最接近的异常,并且接受任何异常

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(IOException.class)
public @ResponseBody ExceptionDetails handleIOException(IOException e) {
    return handleException(e);
}

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(NullPointerException.class)
public @ResponseBody ExceptionDetails handleNPException(NullPointerException e) {
    return handleException(e);
}

SpringExceptionHandler的工作方式有点像“尝试并捕获”

当控制器有异常且有本地异常处理程序时,请求将由本地异常处理程序处理。现在,如果它没有找到局部的,那么我们尝试寻找全局的

在您的情况下,本地异常处理程序处理所有异常,因此不会调用全局异常处理程序

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(IOException.class)
public @ResponseBody ExceptionDetails handleIOException(IOException e) {
    return handleException(e);
}

@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(NullPointerException.class)
public @ResponseBody ExceptionDetails handleNPException(NullPointerException e) {
    return handleException(e);
}