1. 程式人生 > >spring boot 中統一異常處理

spring boot 中統一異常處理

map handler this internal col message static pub 處理

基於 spring boot 對異常處理的不友好,現在通過其他的方式來統一處理異常

步驟一:自定義異常類

public class UserNotExistException extends RuntimeException{
    private static final long serialVersionUID = -1574716826948451793L;

    private String id;

    public UserNotExistException(String id){
        super("user not exist");
        
this.id = id; } public String getId() { return id; } public void setId(String id) { this.id = id; } }

步驟二:定義異常處理類

@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(UserNotExistException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    
public Map<String, Object> handleUserNotExistsException(UserNotExistException e) { Map<String, Object> map = new HashMap<>(); map.put("id", e.getId()); map.put("message", e.getMessage()); return map; } }

步驟三:控制層拋出異常

  @GetMapping("/{id:\\d+}
") public void get(@PathVariable String id) { throw new UserNotExistException(id); }

spring boot 中統一異常處理