在spring中,可以定义一个全局异常处理handler,当有异常的时候,进行拦截处理。
import com.idss.argus.common.Constant;
import com.idss.argus.common.ResponseUtil;
import org.springframework.http.HttpStatus;
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.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@ControllerAdvice
public class
GlobalExceptionHandler extends ResponseEntityExceptionHandler {
/**
* 最大兜底异常,跳500页面
* @param request
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
//设置 response 状态码
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> jsonHandler(HttpServletRequest request,Exception e) throws Exception {
e.printStackTrace();
return ResponseUtil.buildResultMap(Constant.STATUS_FAIL, null, "程序异常", null);
}
/**
* 资产校验异常
* @param e
* @return
* @throws Exception
*/
@ExceptionHandler(value = IdssArgusException.class)
@ResponseBody
public Map<String, Object> handleIdssArgusException(IdssArgusException e) throws Exception {
return ResponseUtil.buildResultMap(Constant.STATUS_FAIL,null,e.getErrorList(),null);
}
}
validated 数据校验
@Validated 数据校验,失败的话会抛出MethodArgumentNotValidException 异常,这样我们可以利用这个特性,做全局校验,进行异常返回。业务层的异常
需要自己自定义异常,然后在handler中进行处理,这样就不需要在Controller中进行异常处理了。
//业务类异常
public class BusinessException extends RuntimeException {
public BusinessException(String message){
super(message);
}
}
@Service
public class DogService {
@Transactional
public Dog update(Dog dog){
// some database options
// 模拟狗狗新名字与其他狗狗的名字冲突
BSUtil.isTrue(false, "狗狗名字已经被使用了...");
// update database dog info
return dog;
}
}
public static void isTrue(boolean expression, String error){
if(!expression) {
throw new BusinessException(error);
}
}