我创建了一个定义如下的 spring boot 应用程序:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
Run Code Online (Sandbox Code Playgroud)
我还为这个应用程序创建了一个带有请求映射的 RestController
然后我创建了一个特定的异常:
public class MyOwnException extends Exception {
public MyOwnException (String message) {
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
然后定义了一个用于全局处理我所有异常的类
@ControllerAdvice(annotations = RestController.class)
public class MyOwnExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MyOwnException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "File or folder is unwrittable")
public @ResponseBody
ExceptionJSONInfo handleMyOwnException(
HttpServletRequest request, Exception ex) {
ExceptionJSONInfo response = new ExceptionJSONInfo();
response.setUrl(request.getRequestURL().toString());
response.setMessage(ex.getMessage());
return response; …Run Code Online (Sandbox Code Playgroud) spring ×1