异常处理
1)引入springmvc依赖包
<!--引入异常处理-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
2)创建异常信息枚举
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public enum ExceptionEnum {
PARENT_ID_CANNOT_BE_NULL(400,"分类父ID不能为空!")
;
private int code;
private String msg;
}
2)创建异常结果
import cn.wangkf.common.enums.ExceptionEnum;
import lombok.Data;
@Data
public class ExceptionResult {
private int status;
private String message;
private Long timestamp;
public ExceptionResult(ExceptionEnum em){
this.status = em.getCode();
this.message = em.getMsg();
this.timestamp = System.currentTimeMillis();
}
}
3)编写自定义异常类
import cn.wangkf.common.enums.ExceptionEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
@Getter
public class LgException extends RuntimeException {
private ExceptionEnum exceptionEnum;
}
4)编写全局异常处理类
import cn.wangkf.common.enums.ExceptionEnum;
import cn.wangkf.common.exception.LgException;
import cn.wangkf.common.vo.ExceptionResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class CommonExceptionHandler {
/*@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> handleException(RuntimeException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}*/
@ExceptionHandler(LgException.class)
public ResponseEntity<String> handleException(LgException e){
ExceptionEnum em = e.getExceptionEnum();
return ResponseEntity.status(em.getCode()).body(em.getMsg());
}
}
5)异常抛出测试
/**
* 保存
* @return
* 异常处理demo
*
*/
@PostMapping
public ResponseEntity<Category> saveCategory(Category category){
if (category.getParentId() == null){
//throw new RuntimeException("分类父ID不能为空!");
throw new LgException(ExceptionEnum.PARENT_ID_CANNOT_BE_NULL);
}
category = categoryService.saveCategoryDemo(category);
return ResponseEntity.status(HttpStatus.CREATED).body(category);
}