一.编写异常枚举类里面解写自己的异常
package com.yukkso.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@Getter
@NoArgsConstructor
public enum ExceptionEnum {
PRICE_CANNOT_NULL(400,"价格不能为空"),
COMMODITY_CANNOT_FIND(404,"商品找不到"),
ID_CANNOT_FIND(404,"商品找不到"),
;
private Integer code;
private String msg;
}
二.自己写一个通用的异常类,记住一定要继承一个类
package com.yukkso.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class LtypException extends RuntimeException {
private ExceptionEnum exceptionEnum;
}
三.编写异常结果处理
package com.yukkso.exception;
public class ExceptionResult {
private Integer status;
private String message;
public ExceptionResult(ExceptionEnum e){
this.status=e.getCode();
this.message=e.getMsg();
}
}
四.编写异常通知处理
package com.yukkso.exception;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class CommonExceptionHandler {
@ExceptionHandler(LtypException.class)
public ResponseEntity<ExceptionResult> responseEntity(LtypException e){
return ResponseEntity.status(e.getExceptionEnum().getCode())
.body(new ExceptionResult(e.getExceptionEnum()));
}
}
五.在自己代码中使用
@GetMapping("/get")
public String selectAllUser(HttpServletRequest request) {
try {
System.out.println("URI-----"+request.getRequestURI());
System.out.println("URL-------"+request.getRequestURL().toString());
System.out.println("协议-------"+request.getScheme());
System.out.println("域名-------"+request.getServerName());
System.out.println("项目名-------"+request.getContextPath());
System.out.println("请求路径-------"+request.getServletPath());
System.out.println("端口-------"+request.getServerPort());
System.out.println(System.getProperty("user.dir")+File.separator+request.getContextPath());
ApplicationHome applicationHome=new ApplicationHome(this.getClass());
System.out.println();
System.out.println(System.getProperty("user.dir"));
if (!StringUtils.isEmpty(System.getProperty("user.dir"))){
//这里为我自己编写的异常
throw new LtypException(ExceptionEnum.COMMODITY_CANNOT_FIND);
}
System.out.println( this.getClass().getResource("/").getPath());
} catch (Exception e) {
e.printStackTrace();
}
return "";
}