首页 > 编程语言 > 详细

Spring 对Controller异常的统一处理

时间:2019-04-28 00:52:35      阅读:145      评论:0      收藏:0      [点我收藏+]

对于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<String, Object> handleUserNotExistException(UserNotExitException ex){
        Map<String, Object> result = new HashMap<>();
        result.put("id", ex.getId());
        result.put("message", ex.getMessage());     
        return result;
    }
}

 

Spring 对Controller异常的统一处理

原文:https://www.cnblogs.com/maple92/p/10781056.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!