经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
spring boot 自定义异常
来源:cnblogs  作者:lxw_thinker  时间:2019/2/21 9:48:37  对本文有异议

SpringBoot自定义异常以及异常处理

 在web项目中,我们可能需要给前端返回不同的提示码。例如:401表示没有权限,500代表位置异常,200代表请求成功等。但是这些提示码远远不能满足我们返回给前端的提示,可能还需要我们自定义错误码给前端,前端获取相应的错误码以及错误信息,展示到页面中。

使用自定义异常可以解决这些返回值,利用自定义异常以及对异常的处理,可以在返回的时候自定义我们的返回码以及错误信息等。

一、自定义异常类

  1. /**
  2.  * @author: lxw
  3.  * @Date: 2019/2/16 20:00
  4.  * @email:
  5.  * @Description: 自定义异常(继承运行时异常) */public class ExceptionUtils extends RuntimeException {private static final long serialVersionUID = 1L;/** * 错误编码     */private int code;/** * 消息是否为属性文件中的Key     */private boolean propertiesKey = true;/** * 构造一个基本异常.
  6.      *
  7.      * @param message 信息描述     */public ExceptionUtils(String message) {super(message);
  8.     }/** * 构造一个基本异常.
  9.      *
  10.      * @param code 错误编码
  11.      * @param message   信息描述     */public ExceptionUtils(int code, String message) {this(code, message, true);
  12.     }/** * 构造一个基本异常.
  13.      *
  14.      * @param code 错误编码
  15.      * @param message   信息描述     */public ExceptionUtils(int code, String message, Throwable cause) {this(code, message, cause, true);
  16.     }/** * 构造一个基本异常.
  17.      *
  18.      * @param code     错误编码
  19.      * @param message       信息描述
  20.      * @param propertiesKey 消息是否为属性文件中的Key     */public ExceptionUtils(int code, String message, boolean propertiesKey) {super(message);this.setCode(code);this.setPropertiesKey(propertiesKey);
  21.     }/** * 构造一个基本异常.
  22.      *
  23.      * @param code 错误编码
  24.      * @param message   信息描述     */public ExceptionUtils(int code, String message, Throwable cause, boolean propertiesKey) {super(message, cause);this.setCode(code);this.setPropertiesKey(propertiesKey);
  25.     }/** * 构造一个基本异常.
  26.      *
  27.      * @param message 信息描述
  28.      * @param cause   根异常类(可以存入任何异常)     */public ExceptionUtils(String message, Throwable cause) {super(message, cause);
  29.     }public int getCode() {return code;
  30.     }public void setCode(int code) {this.code = code;
  31.     }public boolean isPropertiesKey() {return propertiesKey;
  32.     }public void setPropertiesKey(boolean propertiesKey) {this.propertiesKey = propertiesKey;
  33.     }
  34.  
  35. }

二、自定义异常处理

  1. import com.modules.common.utils.RUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.dao.DuplicateKeyException;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;import org.springframework.web.servlet.NoHandlerFoundException;/**
  2.  * @author: lxw
  3.  * @Date: 2019/2/16 20:00
  4.  * @email:
  5.  * @Description: 自定义异常处理 */@RestControllerAdvicepublic class RExceptionUtilsHandler {private Logger logger = LoggerFactory.getLogger(getClass());/** * 处理自定义异常     */@ExceptionHandler(ExceptionUtils.class)public RUtils handleRRException(ExceptionUtils e) {
  6.         RUtils r = new RUtils();
  7.         r.put("code", e.getCode());
  8.         r.put("msg", e.getMessage());return r;
  9.     }/** * 未找到路径异常处理     */@ExceptionHandler(NoHandlerFoundException.class)public RUtils handlerNoFoundException(Exception e) {
  10.         logger.error(e.getMessage(), e);return RUtils.error(404, "路径不存在,请检查路径是否正确");
  11.     }/** * 数据库异常处理     */@ExceptionHandler(DuplicateKeyException.class)public RUtils handleDuplicateKeyException(DuplicateKeyException e) {
  12.         logger.error(e.getMessage(), e);return RUtils.error("数据库中已存在该记录");
  13.     }/** * 普通异常处理     */@ExceptionHandler(Exception.class)public RUtils handleException(Exception e) {
  14.         logger.error(e.getMessage(), e);return RUtils.error();
  15.     }
  16. }

三、自定义返回

  1. package com.modules.common.utils;import java.util.HashMap;import java.util.Map;/**
  2.  * @author: lxw
  3.  * @Date: 2019/2/19 11:19
  4.  * @email:
  5.  * @Description: 自定义返回值 */public class RUtils extends HashMap<String, Object> {private static final long serialVersionUID = 1L;/** * 默认正常返回,使用new RUtils()就可以返回     */public RUtils() {
  6.         put("code", 0);
  7.     }/** * 表示异常     */public static RUtils error() {return error(500, "未知异常,请联系管理员");
  8.     }public static RUtils error(String msg) {return error(500, msg);
  9.     }/** * 自定义异常错误码     */public static RUtils error(int code, String msg) {
  10.         RUtils r = new RUtils();
  11.         r.put("code", code);
  12.         r.put("msg", msg);return r;
  13.     }/** * 带信息的正常返回     */public static RUtils ok(String msg) {
  14.         RUtils r = new RUtils();
  15.         r.put("msg", msg);return r;
  16.     }public static RUtils ok(Map<String, Object> map) {
  17.         RUtils r = new RUtils();
  18.         r.putAll(map);return r;
  19.     }public static RUtils ok() {return new RUtils();
  20.     }
  21.  
  22.     @Overridepublic RUtils put(String key, Object value) {super.put(key, value);return this;
  23.     }
  24. }

四、测试输出

  1. /**
  2.  * @author: lxw
  3.  * @Date: 2018/10/19 19:36
  4.  * @email: 1229703575@qq.com
  5.  * @Description: 测试文件 */@RestController
  6. @RequestMapping("/")public class TestController {   /** * 测试自定义异常
  7.      *
  8.      * @return RUtils     */@ApiOperation(value = "测试自定义异常", notes = "测试自定义异常")
  9.     @GetMapping(value = "/exceptionTest")public RUtils exceptionTest() {
  10.         String msg = new ExceptionUtils(500, "测试异常").getMessage();int errorCode = new ExceptionUtils(500, "测试异常").getCode();return RUtils.error(errorCode, msg);
  11.     }     
  12. }

五、输出结果

  1. {"msg":"测试异常","code":500}

  

原文链接:http://www.cnblogs.com/lxwthinker/p/10402965.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号