Springboot自定义异常处理

时间:2023-03-09 19:27:07
Springboot自定义异常处理

1.自定义异常类

import lombok.Data;

@Data
public class UserException extends RuntimeException {
private Long id; public UserException(Long id) {
super("user not exist");
this.id = id;
} public UserException(String message, Long id) {
super(message);
this.id = id;
}
}

自定义异常类

2.编写异常处理handler

import java.util.HashMap;
import java.util.Map; @ControllerAdvice
public class ControllerExceptionHandler {
@ExceptionHandler(UserException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String,Object> handlerUserNotExistException(UserException ex){
Map<String,Object> result=new HashMap<>();
result.put("id",ex.getId());
result.put("message",ex.getMessage());
return result;
}
}

异常处理handler

3.使用过程

Springboot自定义异常处理