900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > Springboot 自定义全局异常处理

Springboot 自定义全局异常处理

时间:2019-02-17 15:19:29

相关推荐

Springboot 自定义全局异常处理

在项目根包目录下新建 exception.base 包

新建BaseException 继承 RuntimeException

package com.ddz.errordemo.handler;/*** 基础异常类* @author Lenovo* @date /4/26*/public class BaseException extends RuntimeException {/*** 所属模块*/private String module;/*** 错误码*/private String code;/*** 错误码对应的参数*/private Object[] args;/*** 错误消息*/private String defaultMessage;public BaseException(String module, String code, Object[] args, String defaultMessage) {this.module = module;this.code = code;this.args = args;this.defaultMessage = defaultMessage;}public BaseException(String module, String code, Object[] args) {this(module, code, args, null);}public BaseException(String module, String defaultMessage) {this(module, null, null, defaultMessage);}public BaseException(String code, Object[] args) {this(null, code, args, null);}public BaseException(String defaultMessage) {this(null, null, null, defaultMessage);}public String getModule() {return module;}public void setModule(String module) {this.module = module;}public String getCode() {return code;}public void setCode(String code) {this.code = code;}public Object[] getArgs() {return args;}public void setArgs(Object[] args) {this.args = args;}public String getDefaultMessage() {return defaultMessage;}public void setDefaultMessage(String defaultMessage) {this.defaultMessage = defaultMessage;}}

根据自己的需要新建业务异常类

package com.ddz.errordemo.exception;import com.ddz.errordemo.exception.base.BaseException;/*** 用户信息异常类*/public class UserException extends BaseException{private static final long serialVersionUID = 1L;public UserException(String code, Object[] args){super("user", code, args, null);}}

在项目根包目录下新建 exception.handler包;

新建RestExceptionHandler 异常处理类

package com.ddz.errordemo.exception.handler;import com.ddz.errordemo.exception.base.BaseException;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;import javax.servlet.http.HttpServletRequest;/*** @author Lenovo* @date /4/26*/@RestControllerAdvicepublic class RestExceptionHandler {@ExceptionHandler(Exception.class)public Object exception(HttpServletRequest request, Exception e) {return request.getRequestURL() + "全局异常" + e.getMessage();}@ExceptionHandler(NullPointerException.class)public Object nullException(Exception e) {return "空指针" + e.getMessage();}@ExceptionHandler(RuntimeException.class)public Object busException(BaseException e) {return "模块" + e.getModule() + "异常码:" + e.getCode() + "异常信息:" + e.getMessage();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。