BaseExceptionHandler
package com.ihrm.common.exception;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 全局异常
*/
@ControllerAdvice
public class BaseExceptionHandler {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Result error(HttpServletRequest request, HttpServletResponse response,
Exception e){
if (e.getClass()==CommonException.class){
//类型装换
CommonException ce = (CommonException)e;
Result result = new Result(ce.getResultCode());
return result;
}else {
Result result = new Result(ResultCode.SERVER_ERROR);
return result;
}
}
}
CommonException
package com.ihrm.common.exception;
import com.ihrm.common.entity.ResultCode;
import lombok.Getter;
/**
* 自定义异常
*/
@Getter
public class CommonException extends Exception {
private ResultCode resultCode;
public CommonException(ResultCode resultCode){
this.resultCode=resultCode;
}
}