本文共 815 字,大约阅读时间需要 2 分钟。
1.自定义异常类
import lombok.Data;@Datapublic 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;@ControllerAdvicepublic class ControllerExceptionHandler { @ExceptionHandler(UserException.class) @ResponseBody @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public MaphandlerUserNotExistException(UserException ex){ Map result=new HashMap<>(); result.put("id",ex.getId()); result.put("message",ex.getMessage()); return result; }}
转载地址:http://zhtax.baihongyu.com/