1.application.properties配置中加入:
## global exception ##
#出现错误时, 直接抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
#不要为我们工程中的资源文件建立映射
spring.resources.add-mappings=false
2.创建全局异常处理类:
import com.my.iot.app.entity.dto.HttpResponse;
import com.my.iot.app.enums.CodeEnum;
import org.springframework.http.HttpStatus;
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 org.springframework.web.servlet.NoHandlerFoundException;
@RestControllerAdvice
public class GlobalControllerExceptionHandler {
/**
* 前端参数错误 400
*
* @param exception
* @return
*/
@ExceptionHandler(value = {MethodArgumentTypeMismatchException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public HttpResponse methodArgumentTypeMismatchException(MethodArgumentTypeMismatchException exception) {
exception.printStackTrace();
return new HttpResponse(CodeEnum.TYPEERROR.getKey(), CodeEnum.TYPEERROR.getValue(), null);
}
/**
* 请求路径错误 404
*
* @param exception
* @return
*/
@ExceptionHandler(value = {NoHandlerFoundException.class})
@ResponseStatus(HttpStatus.NOT_FOUND)
public HttpResponse noHandlerFoundException(NoHandlerFoundException exception) {
exception.printStackTrace();
return new HttpResponse(CodeEnum.NOMAPPING.getKey(), CodeEnum.NOMAPPING.getValue(), null);
}
/**
* 运行时异常 500
*
* @param re
* @return
*/
@ExceptionHandler(value = {RuntimeException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public HttpResponse runtimeException(RuntimeException re) {
re.printStackTrace();
return new HttpResponse(CodeEnum.ERROR.getKey(), CodeEnum.ERROR.getValue(), null);
}
}
其中HttpResponse:
import java.io.Serializable;
public class HttpResponse implements Serializable {
private Integer code;//响应码
private String message;//响应说明
private Object data;//响应数据
public HttpResponse() {
}
public HttpResponse(Integer code, String message, Object data) {
this.code = code;
this.message = message;
this.data = data;
}
@Override
public String toString() {
return "HttpResponse{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
'}';
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}