1、返回类
import java.io.Serializable;
public class ResponseInfo implements Serializable {
private static final long serialVersionUID = -4417715614021482064L;
private String code;
private String message;
public ResponseInfo(String code, String message) {
super();
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2、异常处理类
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.UnsatisfiedServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import com.xx.xx.xx.ResponseInfo;
/**
* springmvc异常处理
*
*/
@RestControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler({ IllegalArgumentException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseInfo badRequestException(IllegalArgumentException exception) {
return new ResponseInfo(HttpStatus.BAD_REQUEST.value() + "", exception.getMessage());
}
@ExceptionHandler({ AccessDeniedException.class })
@ResponseStatus(HttpStatus.FORBIDDEN)
public ResponseInfo badRequestException(AccessDeniedException exception) {
return new ResponseInfo(HttpStatus.FORBIDDEN.value() + "", exception.getMessage());
}
@ExceptionHandler({ MissingServletRequestParameterException.class, HttpMessageNotReadableException.class,
UnsatisfiedServletRequestParameterException.class, MethodArgumentTypeMismatchException.class })
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseInfo badRequestException(Exception exception) {
return new ResponseInfo(HttpStatus.BAD_REQUEST.value() + "", exception.getMessage());
}
@ExceptionHandler(org.springframework.web.bind.MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseInfo MethodArgumentNotValidException(org.springframework.web.bind.MethodArgumentNotValidException e) {
ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
//参数检验出错
return new ResponseInfo(HttpStatus.BAD_REQUEST.value()+"",objectError.getDefaultMessage());
}
@ExceptionHandler(Throwable.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseInfo exception(Throwable throwable) {
//系统异常
return new ResponseInfo(HttpStatus.INTERNAL_SERVER_ERROR.value() + "", throwable.getMessage());
}
}
网友评论