在项目开发中经常会遇到统一异常处理的问题,在springMVC中有一种解决方式,使用ExceptionHandler.
1.全局异常处理的结果类:
package com.zhourui.business.common.exception.advice;
import com.zhourui.business.common.exception.enums.ExceptionEnum;
import lombok.Data;
/**
* @author zhourui
* @date 2018/9/15
*
* 自定义异常结果类
*/
@Data
public class ExceptionResult {
private int status;
private String message;
private long timestamp;
public ExceptionResult(ExceptionEnum em) {
this.status = em.value();
this.message = em.message();
this.timestamp = System.currentTimeMillis();
}
}
2.异常枚举类:
package com.zhourui.business.common.exception.enums;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
/**
* @author zhourui
* @date 2018/9/15
*/
@NoArgsConstructor
@AllArgsConstructor
public enum ExceptionEnum {
PASSWORD_ERRO(500,"密码错误"),
USER_EMPTY(500,"请输入用户名,密码"),
TOKEN_INVALID(403,"token鉴权失败"),
STATUS_ERRO(400,"状态值错误"),
;
int value;
String message;
public int value() {
return this.value;
}
public String message() {
return this.message;
}
}
3.全局异常类
package com.zhourui.business.common.exception.advice;
import com.zhourui.business.common.exception.enums.ExceptionEnum;
import lombok.Getter;
/**
* @author bystander
* @date 2018/9/15
*
* 自定义异常类
*/
@Getter
public class GlobalException extends RuntimeException {
private ExceptionEnum exceptionEnum;
public GlobalException(ExceptionEnum exceptionEnum) {
this.exceptionEnum = exceptionEnum;
}
}
4.全局异常处理类
package com.zhourui.business.common.exception.advice;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* @author bystander
* @date 2018/9/15
*
* 自定义异常处理
*/
@Slf4j
@ControllerAdvice
public class BasicExceptionHandler {
@ExceptionHandler(GlobalException.class)
public ResponseEntity<ExceptionResult> handleException(GlobalException e) {
return ResponseEntity.status(e.getExceptionEnum().value())
.body(new ExceptionResult(e.getExceptionEnum()));
}
}
5.异常处理测试类
package com.zhourui.business.controller.test;
import com.zhourui.business.common.exception.advice.GlobalException;
import com.zhourui.business.common.exception.enums.ExceptionEnum;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author zhourui
* @date 2019/11/17 11:02
*/
@RestController
@RequestMapping
public class TestController {
@RequestMapping("/hello")
public ResponseEntity<TestBean> testJsonSerializer(@RequestBody TestBean t){
if (t.getType()==0){
throw new GlobalException(ExceptionEnum.STATUS_ERRO);
}
return ResponseEntity.ok().body(t);
}
}
6.postman调用测试