Spring Boot 自定义异常处理实例

版权声明:士,不可以不弘毅,任重而道远 https://blog.csdn.net/superbeyone/article/details/84557491


Spring Boot 自定义异常处理实例

/**
 * @Project: tdt-security
 * @ClassName: UserNotExistException
 * @Author: Mr.superbeyone
 * @Time: 2018-11-25 23:06
 * @Description: 自定义用户表不存在异常
 **/

public class UserNotExistException extends RuntimeException {

    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;
    }
}
import com.tdt.security.exception.UserNotExistException;
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 java.util.HashMap;
import java.util.Map;

/**
 * @Project: tdt-security
 * @ClassName: ControllerExceptionHandler
 * @Author: Mr.superbeyone
 * @Time: 2018-11-25 23:13
 * @Description: Controller异常控制器
 **/
@ControllerAdvice
public class ControllerExceptionHandler {

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

github 项目源码地址

猜你喜欢

转载自blog.csdn.net/superbeyone/article/details/84557491
今日推荐