spring自己设置全局异常
背景
在springmvc的controller中程序员经常要封装错误对象返回错误,前台显示错误文案。通过spring的异常解决器,来进行自己设置异常解决
学习目标
学习全局异常阻拦器解决controller所有的异常的返回封装
定义枚举异常码,设计自己设置异常
案列
创立枚举异常码,定义系统异常情况
/**
* @author tianjz
*/
public enum ResultEnum {
? ? SUCCESS(“0”, “成功”),
? ? PARAMETER_ERROR(“1000”, “请求参数错误”),
? ? UNKNOWN_DATA_FORMAT(“1001”, “未知数据格式”),
? ? UNDEFINED(“1002”, “未定义或者者错误的接口”),
? ? ERROR(“2000”, “响应错误”),
? ? EMPTY(“2001”, “空数据”);
? ? private String code;
? ? private String msg;
? ? ResultEnum(String code, String msg) {
? ? ? ? this.code = code;
? ? ? ? this.msg = msg;
? ? }
? ? public String getCode() {
? ? ? ? return code;
? ? }
? ? public String getMsg() {
? ? ? ? return msg;
? ? }
}
import com.cms2.imitative.commons.ResultEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @author tianjz
*/
@Data
@AllArgsConstructor
public class StudyRuntimeException extends RuntimeException {
? ? /**
? ? * 异常码
? ? */
? ? private ResultEnum errorCode;
? ? /**
? ? * 异常形容
? ? */
? ? private String errorMessage;
? ? /**
? ? * Constructs a new runtime exception with {@code null} as its
? ? * detail message.? The cause is not initialized, and may subsequently be
? ? * initialized by a call to {@link #initCause}.
? ? */
? ? public StudyRuntimeException(ResultEnum errorCode) {
? ? ? ? this.errorCode = errorCode;
? ? }
}
具体阻拦逻辑 :
通过异常instanceof判断出自己设置异常
取出异常码,通过json方式返回给前台
具体阻拦流程:
springboot :<不要不记得注入 >

springmvc :
请在xml中自行注入
import com.alibaba.fastjson.JSONObject;
import com.cms2.imitative.commons.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author tianjz
*/
@Component
@Slf4j
public class GlobalExceptionInterceptor implements HandlerExceptionResolver {
? ? @Override
? ? public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
? ? ? ? ModelAndView view = new ModelAndView();
? ? ? ? Home(“全局异常阻拦”);
? ? ? ? try {
? ? ? ? ? ? if (e instanceof StudyRuntimeException) {
? ? ? ? ? ? ? ? setJsonErrorResponse(response, ((StudyRuntimeException) e).getErrorCode());
? ? ? ? ? ? } else {
? ? ? ? ? ? ? ? setJsonErrorResponse(response, ResultEnum.ERROR);
? ? ? ? ? ? }
? ? ? ? } catch (IOException ex) {
? ? ? ? ? ? ex.printStackTrace();
? ? ? ? ? ? log.error(“全局异常捕获失败,起因 :{},{}”,ex.getMessage(),GlobalExceptionInterceptor.class);
? ? ? ? ? ? return null;
? ? ? ? }
? ? ? ? return view;
? ? }
? ? private void setJsonErrorResponse(HttpServletResponse response, ResultEnum error) throws IOException {
? ? ? ? Map<String, String> map = new LinkedHashMap<>();
? ? ? ? // 设置状态码
? ? ? ? response.setStatus(HttpStatus.OK.value());
? ? ? ? // 设置ContentType
? ? ? ? response.setContentType(MediaType.APPLICATION_JSON_VALUE);
? ? ? ? // 避免乱码
? ? ? ? response.setCharacterEncoding(“UTF-8”);
? ? ? ? map.put(“code”, error.getCode());
? ? ? ? map.put(“msg”, error.getMsg());
? ? ? ? Object json = JSONObject.toJSON(map);
? ? ? ? response.getWriter().write(json.toString());
? ? }
}
demo代码 :
/**
* @author tianjz
*/
@RestController
@RequestMapping(“/error”)
public class ExceptionTest {
? ? @GetMapping(“/{errorCode}”)
? ? public String test(@PathVariable(“errorCode”)String error) {
? ? ? ? switch (error) {
? ? ? ? ? ? case “1000”:
? ? ? ? ? ? ? ? throw new StudyRuntimeException(ResultEnum.PARAMETER_ERROR);
? ? ? ? ? ? case “2001”:
? ? ? ? ? ? ? ? throw new StudyRuntimeException(ResultEnum.EMPTY);
? ? ? ? ? ? default:
? ? ? ? ? ? ? ? System.out.println(“啥也没有”);
? ? ? ? }
? ? ? ? return null;
? ? }
}
测试效果 :
1000

2001

————————————————
来源:csdn原文链接:https://blog.csdn.net/weixin_44768087/article/details/102919042
需要《spring技术内幕.pdf》文档,私信“资料”获取!


1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » spring自己设置全局异常