赞
踩
目录
实现的功能如下:
1.全局捕获异常,当出现错误抛出一个友好的提示给前端。
2.手动在指定处直接抛出一个有好的提示,终止当前操作。
手动抛出异常,在那个层都可以直接捕获异常,只要符合条件。
实现效果
除此之外,只要程序出现异常,可以设定一个默认的提示,返回给前端。
主要用于直接调用枚举类,传递给定的信息便于维护。
- public enum FrontMonitorErrorCode {
- NULL_TENANT_KEY("001","tenantKey为空"),
- UNKNOWN_ERROR("002","未知错误,请联系管理员");
- private String value;
- private String desc;
- private FrontMonitorErrorCode(String value, String desc) {
- this.setValue(value);
- this.setDesc(desc);
- }
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- public String getDesc() {
- return desc;
- }
- public void setDesc(String desc) {
- this.desc = desc;
- }
- @Override
- public String toString() {
- return "[" + this.value + "]" + this.desc;
- }
- }
- public class FrontMonitorException extends RuntimeException {
-
- private static final long serialVersionUID = 1L;
-
- public FrontMonitorException(FrontMonitorErrorCode errorCode) {
- super(errorCode.toString());
- }
- }
主要用于返回异常信息。
-
- import org.springframework.web.bind.annotation.ControllerAdvice;
- import org.springframework.web.bind.annotation.ExceptionHandler;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- /**
- *
- * @Date:Created in 11:31 2022/3/8
- */
- @ControllerAdvice
- public class FrontMonitorExceptionHandler {
-
- @ExceptionHandler(value = FrontMonitorException.class)
- @ResponseBody
- public String exceptionHandler(FrontMonitorException e) {
- return e.getMessage();
- }
-
-
- @ExceptionHandler(value = Exception.class)
- @ResponseBody
- public String baseHandler() {
- return "服务器出现异常,请联系管理员!";
- }
- }
然后在需要的地方直接抛出异常就可以了。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。