赞
踩
1,ResponseVo包装类
package com.zhiyou100.demo.vo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /**包装类,将数据包装成json格式返回给前端 * @author zhangfan * @date 2019/10/9 */ @Data //生成toString和get&&set @NoArgsConstructor //生成无参构造方法 @AllArgsConstructor //生成所有有参构造方法 public class ResponseVo<T> { private Integer code; private String message; private T data; }
2,自定义异常类
package com.zhiyou100.demo.exception; /**定义异常处理类 * 1.继承RuntimeException * 2.定义属性code,返回错误码 * 3.写get方法 * 4.写入有参构造方法 * 5.message用来输出异常信息 * @author zhangfan * @date 2019/10/9 */ public class MyException extends RuntimeException{ private Integer code; public MyException(Integer code,String message){ super(message); this.code = code; } public Integer getCode() { return code; } }
3,Controller层
package com.zhiyou100.demo.controller; import com.zhiyou100.demo.exception.MyException; import com.zhiyou100.demo.vo.ResponseVo; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /**Controller层的异常处理 * 1.@RestControllerAdvice注解说明是异常处理 * 2.定义方法返回值为ResponseVo * 3.@ExceptionHandler(MyException.class)注解绑定我的异常类 * @author zhangfan * @date 2019/10/9 */ @RestControllerAdvice public class ExceptionController { @ExceptionHandler(MyException.class) //绑定异常类 public ResponseVo handlerMyException(MyException ex){ return new ResponseVo(ex.getCode(),ex.getMessage(),null); } }
异常的使用比如登录时
/** * 管理员登录 * @param account 账号 * @param password 密码 * @return */ @Override public Admin findAdminAccountAndPassword(String account, String password) { Admin findAccountAdmin = adminDao.findAccount(account); if (findAccountAdmin == null){ throw new MyException(403001,"账号不存在"); } Admin findAccountAndPasswordAdmin = adminDao.findAccountAndPassword(account,password); if (findAccountAndPasswordAdmin == null){ throw new MyException(403002,"密码不正确"); } return findAccountAndPasswordAdmin; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。