关于java运行中抛出异常的几种写法
/throw new IllegalArgumentException("请输入正确代码表,要求表名前缀是:"+"666"+"、");throw new IllegalArgumentException("请输入正确代码表,要求表名前缀是:"+"666"+"、");//throw new GuliException(20001,"哈哈哈哈");throw new GuliException(200
·
1.
@Override public PageInfo<Map<String, Object>> selectPage(Integer page, Integer size) { PageHelper.startPage(page,size); List<Map<String,Object>> list= dictMapper.selectPage1(); if (list.size()>0){ throw new IllegalArgumentException("请输入正确代码表,要求表名前缀是:"+"666"+"、"); //throw new GuliException(20001,"哈哈哈哈"); } return new PageInfo<>(list); }
1.1postman运行结果
2.比较优雅的抛出异常
package com.atguigu.yygh.cmn.service.impl; import com.atguigu.yygh.common.result.Result; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @Slf4j @ControllerAdvice public class GlobalExceptionHandler { //自定义异常 @ExceptionHandler(GuliException.class) @ResponseBody //为了返回数据 public Result error(GuliException e) { log.error(e.getMessage()); e.printStackTrace(); return Result.fail(e.getCode()).message(e.getMsg()); } }
package com.atguigu.yygh.cmn.service.impl; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor //生成有参数构造方法 @NoArgsConstructor //生成无参数构造 public class GuliException extends RuntimeException { private Integer code;//状态码 private String msg;//异常信息 }
@Override public PageInfo<Map<String, Object>> selectPage(Integer page, Integer size) { PageHelper.startPage(page,size); List<Map<String,Object>> list= dictMapper.selectPage1(); if (list.size()>0){ //throw new IllegalArgumentException("请输入正确代码表,要求表名前缀是:"+"666"+"、"); throw new GuliException(20001,"哈哈哈哈"); } return new PageInfo<>(list); }
postman测试结果
更多推荐
已为社区贡献3条内容
所有评论(0)