1、创建枚举自定义错误码以及提示:
public enum BizCodeEnume { UNKNOW_EXCEPTION(10000,"系统未知异常"), VALID_EXCEPTION(10001,"参数格式校验失败"); private int code; private String msg; BizCodeEnume(int code,String msg){ this.code =code; this.msg = msg; } public int getCode(){ return code; } public String getMsg() { return msg; } }
2、创建统一处理异常类:
package com.atguigu.gulimall.product.exception; import com.atguigu.common.exception.BizCodeEnume; import com.atguigu.common.utils.R; import lombok.extern.slf4j.Slf4j; import org.springframework.validation.BindingResult; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.HashMap; import java.util.Map; //@ControllerAdvice统一集中异常处理 @Slf4j /*@ControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")*/ //处理com.atguigu.gulimall.product.controller包下抛出的异常 @RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller") public class GulimallExceptionControllerAdvice { //使用@ExceptionHandler注解感知controller包抛出的异常 @ExceptionHandler(value = MethodArgumentNotValidException.class) public R handleVaildException( MethodArgumentNotValidException e){ BindingResult bindingResult = e.getBindingResult(); Map<String,String> errorMap = new HashMap<>();
//将错误信息遍历并且放入map中 bindingResult.getFieldErrors().forEach((fieldError)->{ errorMap.put(fieldError.getField(),fieldError.getDefaultMessage()); }); return R.error(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg()).put("data",errorMap); } @ExceptionHandler(value = Throwable.class) public R handleException(){ return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(),BizCodeEnume.UNKNOW_EXCEPTION.getMsg()); } }
3、选取一个controller为例
高亮部分需要通过设置空接口来区分不同的情况下异常不同处理情况
package com.atguigu.gulimall.product.controller; import java.util.Arrays; import java.util.HashMap; import java.util.Map; //import org.apache.shiro.authz.annotation.RequiresPermissions; import com.atguigu.common.valid.AddGroup; import com.atguigu.common.valid.UpadteGroup; import com.atguigu.common.valid.UpadteStatusGroup; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.atguigu.gulimall.product.entity.BrandEntity; import com.atguigu.gulimall.product.service.BrandService; import com.atguigu.common.utils.PageUtils; import com.atguigu.common.utils.R; import javax.validation.Valid; /** * 品牌 * * @author chenshun * @email linchenguang@gmail.com * @date 2020-05-19 20:39:16 */ @RestController @RequestMapping("product/brand") public class BrandController { @Autowired private BrandService brandService; /** * 列表 */ @RequestMapping("/list") //@RequiresPermissions("product:brand:list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = brandService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{brandId}") //@RequiresPermissions("product:brand:info") public R info(@PathVariable("brandId") Long brandId){ BrandEntity brand = brandService.getById(brandId); return R.ok().put("brand", brand); } /** * 保存 */ @RequestMapping("/save") //@RequiresPermissions("product:brand:save") public R save(@Validated(AddGroup.class) @RequestBody BrandEntity brand/*, BindingResult result*/){ /* if (result.hasErrors()) { Map<String,String> map = new HashMap<>(); //获取检验的错误结果 result.getFieldErrors().forEach((item)->{ String message = item.getDefaultMessage(); //获取错误属性 String field = item.getField(); map.put(field,message); }); return R.error(400, "提交数据不合法").put("data",map);*/ brandService.save(brand); return R.ok(); } /** * 修改 */ @RequestMapping("/update") //@RequiresPermissions("product:brand:update") public R update(@Validated(UpadteGroup.class) @RequestBody BrandEntity brand){ brandService.updateById(brand); return R.ok(); } /** * 修改状态 */ @RequestMapping("/update/status") //@RequiresPermissions("product:brand:update") public R updateStatus(@Validated(UpadteStatusGroup.class) @RequestBody BrandEntity brand){ brandService.updateById(brand); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") //@RequiresPermissions("product:brand:delete") public R delete(@RequestBody Long[] brandIds){ brandService.removeByIds(Arrays.asList(brandIds)); return R.ok(); } }
4、选取一个entiy类为例:
高亮部分使用分组校验:不同情况下不同校验方式----例如groups = {AddGroup.class,UpadteGroup.class},没有指定分组的注解是不生效
package com.atguigu.gulimall.product.entity; import com.atguigu.common.valid.AddGroup; import com.atguigu.common.valid.ListValue; import com.atguigu.common.valid.UpadteGroup; import com.atguigu.common.valid.UpadteStatusGroup; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import lombok.Data; import org.hibernate.validator.constraints.URL; import javax.validation.constraints.*; /** * 品牌 * * @author chenshun * @email linchenguang@gmail.com * @date 2020-05-19 20:39:16 */ @Data @TableName("pms_brand") public class BrandEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 品牌id */ @NotNull(message = "修改必须指定品牌id",groups = {UpadteGroup.class}) @Null(message = "新增必须指定品牌id",groups = {AddGroup.class}) @TableId private Long brandId; /** * 品牌名 */ @NotBlank(message = "品牌名必须提交",groups = {AddGroup.class,UpadteGroup.class}) private String name; /** * 品牌logo地址,新增时不能为空并且符合URL地址格式,而修改时可以为空但必须符合URL地址 */ @NotBlank(groups = {AddGroup.class}) @URL(message = "必须上传正确图片",groups = {AddGroup.class,UpadteGroup.class}) private String logo; /** * 介绍 */ private String descript; /** * 显示状态[0-不显示;1-显示] */ @NotNull(groups = {AddGroup.class, UpadteStatusGroup.class}) @ListValue(vals = {0,1},groups = {AddGroup.class, UpadteStatusGroup.class}) private Integer showStatus; /** * 检索首字母 */ @NotEmpty(groups = {AddGroup.class}) @Pattern(regexp = "^[a-zA-Z]$",message = "范围必须在a-z或A-Z之间",groups = {AddGroup.class,UpadteGroup.class}) private String firstLetter; /** * 排序 */ @NotNull(groups = {AddGroup.class}) @Min(value = 0,message = "排序必须大于等于0",groups = {AddGroup.class,UpadteGroup.class}) private Integer sort; }
5、设置空接口
//1、 public interface UpadteGroup { } //2、 public interface UpadteStatusGroup { } //3、 public interface AddGroup { }