问题描述
问题:@ExceptionHandler(Exception.class)进行全局异常处理,但是我有个方法不想用这个全局异常处理,想使用自己单独的异常处理方式,怎么排除这个方法呢。
解决方案:
方式一
@RestControllerAdvice
@Slf4j
public class AllExceptionHandler {
// 这是一个全局异常处理
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
log.error("全局异常信息:", e);
return "这是全局异常";
}
// 这是局部异常处理,仅适用于tagError方法
@ExceptionHandler(value = { YourSpecificException.class }, tags = { "errorMethod" })
public ResponseEntity<String> handleSpecificException(YourSpecificException e) {
// 特定异常处理逻辑
return "这是局部异常";
}
}
@RestController
public class YourController {
// 这个方法不会使用全局异常处理,而是会使用标记为"errorMethod"的局部处理
@RequestMapping(value = "/your-endpoint", method = RequestMethod.GET)
@Tag(name = "errorMethod")
public String yourMethod() throws YourSpecificException {
// 业务逻辑
throw new YourSpecificException("Some error message");
}
}
方式二
重新自定义一个异常类TestException,使用ExceptionHandler(TestException.class)添加这个自定义异常类,进行异常处理。
这样使用这个异常类的方法就会使用TestException这个异常,不会再去使用Exception这个全局异常处理。
全局异常:
@RestControllerAdvice
@Slf4j
public class AllExceptionHandler {
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
log.error("全局异常信息:", e);
return "这是全局异常";
}
}
自定义异常:
/**
* 自定义异常
*/
public class TestException extends RuntimeException{
}
使用自定义异常的方法:
@RestController
public class TestController {
@ResponseBody
@ExceptionHandler(TestException.class) //使用自定义异常
public String test(){
if(true){
//抛出自定义异常测试
throw new TestException();
}
return "成功";
}
//使用全局异常
@ResponseBody
public String testAll() throws Exception{
if(true){
//抛出全局异常测试
throw new Exception();
}
return "成功";
}
}
总结
ExceptionHandler的注意事项:
Controller类下多个@ExceptionHandler上的异常类型不能出现一样的,否则运行时抛异常。
错误示例:
@RestController
public class TestController {
@ResponseBody
@ExceptionHandler(TestException.class) //使用自定义异常
public String test(){
if(true){
//抛出自定义异常测试
throw new TestException();
}
return "成功";
}
@ResponseBody
@ExceptionHandler(TestException.class) //使用自定义异常
public String test1(){
if(true){
//抛出自定义异常测试
throw new TestException();
}
return "成功";
}
//使用全局异常
@ResponseBody
public String testAll() throws Exception{
if(true){
//抛出全局异常测试
throw new Exception();
}
return "成功";
}
}
这种情况全局异常处理就会报错,正确的方式再创建个自定义异常,两个类型分开使用
重新创建个Test1Exception异常
/**
* 自定义异常
*/
public class Test1Exception extends RuntimeException{
}
@RestController
public class TestController {
@ResponseBody
@ExceptionHandler(TestException.class) //使用自定义异常
public String test(){
if(true){
//抛出自定义异常测试
throw new TestException();
}
return "成功";
}
@ResponseBody
@ExceptionHandler(Test1Exception.class) //使用自定义异常
public String test1(){
if(true){
//抛出自定义异常测试
throw new Test1Exception();
}
return "成功";
}
//使用全局异常
@ResponseBody
public String testAll() throws Exception{
if(true){
//抛出全局异常测试
throw new Exception();
}
return "成功";
}
}