Spring 对Controller异常的统一处理

对于Controller的异常处理,分为两种,一种是对已知的异常处理,一种是未知的异常处理

1、定义自定义异常类

/**
 * @author hzc
 *
 */
public class UserNotExitException extends RuntimeException {

    /**
     *
     */
    private static final long serialVersionUID = -6271509017751433865L;

    private String id;

    public UserNotExitException(String id) {
        super("user not exit");
        this.setId(id);
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

}

2、使用@ControllerAdvice

import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.maple.exception.UserNotExitException;

@ControllerAdvice
public class ControllerExceptionHandle {
    @ExceptionHandler(UserNotExitException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map handleUserNotExistException(UserNotExitException ex){
        Map result = new HashMap<>();
        result.put("id", ex.getId());
        result.put("message", ex.getMessage());
        return result;
    }
}

Original: https://www.cnblogs.com/maple92/p/10781056.html
Author: Topze
Title: Spring 对Controller异常的统一处理

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/582942/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球