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; } }
3.使用过程