1. 程式人生 > >Spring 對Controller異常的統一處理

Spring 對Controller異常的統一處理

runtime object 處理 java ota body ava server per

對於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異常的統一處理