当前位置: 首页> 汽车> 时评 > 兰州画册设计公司_一手网推项目平台_seoul是什么品牌_百度高级搜索

兰州画册设计公司_一手网推项目平台_seoul是什么品牌_百度高级搜索

时间:2025/7/11 0:43:14来源:https://blog.csdn.net/qq_29385297/article/details/146140674 浏览次数: 1次
兰州画册设计公司_一手网推项目平台_seoul是什么品牌_百度高级搜索

自定义异常处理可以帮助我们更好地管理应用程序中的异常,并返回统一的错误响应。

1. 自定义异常类

定义自己的异常类,继承自 RuntimeException 或其他异常类。

public class MyException extends RuntimeException {private String msg;public MyException(String msg) {super(msg);this.msg = msg;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}
}

2. 使用 @ControllerAdvice 和 @ExceptionHandler

@ControllerAdvice 是一个全局的异常处理类,它可以处理整个应用程序中抛出的异常。@ExceptionHandler 用于指定处理特定异常的方法。

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;@ControllerAdvice
public class MyExceptionHandler {@ExceptionHandler(MyException.class)public ResponseEntity<String> MyExceptionHandle(Exception e){return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);}@ExceptionHandler(Exception.class)public ResponseEntity<String> exceptionHandle(Exception e){e.printStackTrace();return new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);}}

3. 创建控制器类,在 Controller 中抛出异常

import com.qvtu.web.exception.MyException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/dish")
public class DishController {@RequestMapping("/del/{i}")public ResponseEntity<String> delDish(@PathVariable String i) {Integer id=Integer.valueOf(i);if (id<0){throw  new MyException("参数错误!");}return new ResponseEntity<>("del success", HttpStatus.OK);}
}

4. 运行测试

启动程序,在浏览器中访问http://localhost:8080/dish/del/1
在这里插入图片描述
在浏览器中访问http://localhost:8080/dish/del/-1
在这里插入图片描述
在浏览器中访问http://localhost:8080/dish/del/a
在这里插入图片描述

关键字:兰州画册设计公司_一手网推项目平台_seoul是什么品牌_百度高级搜索

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: