1:返回统一格式数据
ApiResponse.java
/**
* @program: ticket
* @description: 返回统一格式数据类
* @author: clx
* @create: 2019-09-11 10:41
*/
public class ApiResponse {
//返回 1:正确 0:错误
private int code;
//返回请求状态码
private int status;
//返回结果 success / error
private String result;
//返回 请求数据结果
private Object data;
//返回错误信息对象
private Object error_msg;
//正确结果对象
public ApiResponse success(Object data){
ApiResponse apiResponse=new ApiResponse();
apiResponse.setCode(1);
apiResponse.setStatus(200);
apiResponse.setResult("success");
apiResponse.setData(data);
return apiResponse;
}
//错误对象
public ApiResponse error(int status,Object error_msg){
ApiResponse apiResponse=new ApiResponse();
apiResponse.setCode(0);
apiResponse.setStatus(status);
apiResponse.setResult("error");
apiResponse.setError_msg(error_msg);
return apiResponse;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Object getError_msg() {
return error_msg;
}
public void setError_msg(Object error_msg) {
this.error_msg = error_msg;
}
}
2:返回统一格式数据
import com.alibaba.fastjson.JSON;
import com.heheda.ticket.web.vo.ApiResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* @program: ticket
* @description: 返回统一格式数据
* @author: clx
* @create: 2019-09-11 10:47
*/
@RestControllerAdvice(annotations = RestController.class)
public class ApiResponseHandler implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (o instanceof String){
//自定义请求头的格式
serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
//以JSON 字符串返回
return JSON.toJSONString(new ApiResponse().success(o));
}
else if (o instanceof ApiResponse){
//错误对象
return o;
}
else {
return new ApiResponse().success(o);
}
}
}
3:错误对象
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @program: ticket
* @description: 错误对象
* @author: clx
* @create: 2019-09-11 10:54
*/
public class ErrorVo {
private String localizedMessage;
private String ex_message;
private String message;
private String clazz;
private int lineNumber;
private String fileName;
private boolean nativeMethod;
private String className;
private String methodName;
private String date;
//Date指定格式:yyyy-MM-dd HH:mm:ss
private SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public ErrorVo errorVo(RuntimeException ex,String message){
ErrorVo errorVo=new ErrorVo();
//自定义传入消息提示
errorVo.setMessage(message);
//发生错误的类名
errorVo.setClassName( ex.getStackTrace()[0].getClassName());
//方法名
errorVo.setMethodName(ex.getStackTrace()[0].getMethodName());
errorVo.setFileName(ex.getStackTrace()[0].getFileName());
errorVo.setLineNumber( ex.getStackTrace()[0].getLineNumber());
errorVo.setNativeMethod(ex.getStackTrace()[0].isNativeMethod());
errorVo.setEx_message(ex.getMessage());
errorVo.setLocalizedMessage(ex.getLocalizedMessage());
errorVo.setClazz(ex.getClass().getName());
errorVo.setDate(simpleDateFormat.format(new Date()));
return errorVo;
}
public ErrorVo errorVo(Exception ex,String message){
ErrorVo errorVo=new ErrorVo();
errorVo.setMessage(message);
errorVo.setClassName( ex.getStackTrace()[0].getClassName());
errorVo.setMethodName(ex.getStackTrace()[0].getMethodName());
errorVo.setFileName(ex.getStackTrace()[0].getFileName());
errorVo.setLineNumber( ex.getStackTrace()[0].getLineNumber());
errorVo.setNativeMethod(ex.getStackTrace()[0].isNativeMethod());
errorVo.setEx_message(ex.getMessage());
errorVo.setLocalizedMessage(ex.getLocalizedMessage());
errorVo.setClazz(ex.getClass().getName());
errorVo.setDate(simpleDateFormat.format(new Date()));
return errorVo;
}
public ErrorVo errorVo(VirtualMachineError ex,String message){
ErrorVo errorVo=new ErrorVo();
errorVo.setMessage(message);
errorVo.setClassName( ex.getStackTrace()[0].getClassName());
errorVo.setMethodName(ex.getStackTrace()[0].getMethodName());
errorVo.setFileName(ex.getStackTrace()[0].getFileName());
errorVo.setLineNumber( ex.getStackTrace()[0].getLineNumber());
errorVo.setNativeMethod(ex.getStackTrace()[0].isNativeMethod());
errorVo.setEx_message(ex.getMessage());
errorVo.setLocalizedMessage(ex.getLocalizedMessage());
errorVo.setClazz(ex.getClass().getName());
errorVo.setDate(simpleDateFormat.format(new Date()));
return errorVo;
}
public ErrorVo errorVo(Throwable ex,String message){
ErrorVo errorVo=new ErrorVo();
errorVo.setMessage(message);
errorVo.setClassName(ex.getStackTrace()[0].getClassName());
errorVo.setMethodName(ex.getStackTrace()[0].getMethodName());
errorVo.setFileName(ex.getStackTrace()[0].getFileName());
errorVo.setLineNumber( ex.getStackTrace()[0].getLineNumber());
errorVo.setNativeMethod(ex.getStackTrace()[0].isNativeMethod());
errorVo.setEx_message(ex.getMessage());
errorVo.setLocalizedMessage(ex.getLocalizedMessage());
errorVo.setClazz(ex.getClass().getName());
errorVo.setDate(new Date().toString());
return errorVo;
}
public String getLocalizedMessage() {
return localizedMessage;
}
public void setLocalizedMessage(String localizedMessage) {
this.localizedMessage = localizedMessage;
}
public String getEx_message() {
return ex_message;
}
public void setEx_message(String ex_message) {
this.ex_message = ex_message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getClazz() {
return clazz;
}
public void setClazz(String clazz) {
this.clazz = clazz;
}
public int getLineNumber() {
return lineNumber;
}
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public boolean isNativeMethod() {
return nativeMethod;
}
public void setNativeMethod(boolean nativeMethod) {
this.nativeMethod = nativeMethod;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
}
4:全局异常处理
import com.heheda.ticket.web.vo.ApiResponse;
import com.heheda.ticket.web.vo.error.ErrorVo;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
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.servlet.NoHandlerFoundException;
import java.io.IOException;
/**
* @program: ticket
* @description: 全局异常处理
* @author: clx
* @create: 2019-09-11 10:40
*/
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(RuntimeException.class)
public ApiResponse runtimeExceptionHandler(RuntimeException ex){
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"运行时出错"));
}
//空指针异常
@ExceptionHandler(NullPointerException.class)
public ApiResponse nullPointerExceptionHandler(NullPointerException ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"空指针异常"));
}
//类型转换异常
@ExceptionHandler(ClassCastException.class)
public ApiResponse classCastExceptionHandler(ClassCastException ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"类型转换异常"));
}
//IO异常
@ExceptionHandler(IOException.class)
public ApiResponse iOExceptionHandler(IOException ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"类型转换异常"));
}
//未知方法异常
@ExceptionHandler(NoSuchMethodException.class)
public ApiResponse noSuchMethodExceptionHandler(NoSuchMethodException ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"未知方法异常"));
}
//数组越界异常
@ExceptionHandler(IndexOutOfBoundsException.class)
public ApiResponse indexOutOfBoundsExceptionHandler(IndexOutOfBoundsException ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"数组越界异常"));
}
//400错误
@ExceptionHandler({HttpMessageNotReadableException.class})
public ApiResponse requestNotReadable(HttpMessageNotReadableException ex) {
return new ApiResponse().error(HttpStatus.BAD_REQUEST.value(),
new ErrorVo().errorVo(ex,"400错误"));
}
//400错误
@ExceptionHandler({TypeMismatchException.class})
public ApiResponse requestTypeMismatch(TypeMismatchException ex) {
return new ApiResponse().error(HttpStatus.BAD_REQUEST.value(),
new ErrorVo().errorVo(ex,"400错误"));
}
//404错误
@ExceptionHandler({NoHandlerFoundException.class})
public ApiResponse noHandlerFoundException(NoHandlerFoundException ex) {
return new ApiResponse().error(HttpStatus.NOT_FOUND.value(),
new ErrorVo().errorVo(ex,"找不到相应的路径"));
}
//400错误
@ExceptionHandler({MissingServletRequestParameterException.class})
public ApiResponse requestMissingServletRequest(MissingServletRequestParameterException ex) {
return new ApiResponse().error(HttpStatus.BAD_REQUEST.value(),
new ErrorVo().errorVo(ex,"400错误"));
}
//405错误
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
public ApiResponse request405(HttpRequestMethodNotSupportedException ex) {
return new ApiResponse().error(HttpStatus.METHOD_NOT_ALLOWED.value(),
new ErrorVo().errorVo(ex,"405错误"));
}
//406错误
@ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
public ApiResponse request406(HttpMediaTypeNotAcceptableException ex) {
return new ApiResponse().error(HttpStatus.NOT_ACCEPTABLE.value(),
new ErrorVo().errorVo(ex,"405错误"));
}
//500错误
@ExceptionHandler({ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
public ApiResponse server500(RuntimeException ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"500错误"));
}
//栈溢出
@ExceptionHandler({StackOverflowError.class})
public ApiResponse requestStackOverflow(StackOverflowError ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"栈溢出"));
}
//除数不能为0
@ExceptionHandler({ArithmeticException.class})
public ApiResponse arithmeticException(ArithmeticException ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"除数不能为0"));
}
//其他错误
@ExceptionHandler({Exception.class})
public ApiResponse exception(Exception ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"其他错误"));
}
private ApiResponse resultFormat(Integer code, T ex) {
return new ApiResponse().error(HttpStatus.INTERNAL_SERVER_ERROR.value(),
new ErrorVo().errorVo(ex,"其他错误"));
}
5:异常类体系借鉴:https://blog.csdn.net/Mrs_chens
6:配置404错误:
#出现错误时, 直接抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
#不要为我们工程中的资源文件建立映射
spring.resources.add-mappings=false