Spring想要某个方法不使用全局异常处理

问题描述

问题:@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 "成功";
	}
}

Spring Boot中,可以通过@ControllerAdvice注解来定义全局异常处理器,当系统中某个地方抛出异常时,该异常处理器会进行拦截处理。 以下是一个简单的示例: 1.定义一个自定义异常类,例如: ```java public class MyException extends RuntimeException { public MyException(String message) { super(message); } } ``` 2.定义一个全局异常处理器,例如: ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MyException.class) @ResponseBody public Map<String, Object> handleMyException(MyException e) { Map<String, Object> result = new HashMap<>(); result.put("code", 500); result.put("msg", e.getMessage()); return result; } @ExceptionHandler(Exception.class) @ResponseBody public Map<String, Object> handleException(Exception e) { Map<String, Object> result = new HashMap<>(); result.put("code", 500); result.put("msg", "系统异常,请稍后再试!"); return result; } } ``` 3.在Controller中抛出自定义异常: ```java @RestController public class UserController { @GetMapping("/user/{id}") public User getUser(@PathVariable Long id) { if (id == 1L) { return new User(id, "张三"); } else { throw new MyException("用户不存在!"); } } } ``` 4.测试: 访问http://localhost:8080/user/1,正常返回数据: ```json {"id":1,"name":"张三"} ``` 访问http://localhost:8080/user/2,返回自定义错误信息: ```json {"code":500,"msg":"用户不存在!"} ``` 如果系统中发生其他异常,也会被全局异常处理器拦截并返回统一的错误信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

涛哥是个大帅比

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值