一、@RestControllerAdvice和 @ExceptionHandler拦截异常
package com.lxk.socket.collector.common;
import com.lxk.base.bean.CommonResult;
import com.lxk.base.exception.BusinessRuntimeException;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionResolver {
private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionResolver.class);
/**
* 处理所有不可知异常
*/
@ExceptionHandler(Exception.class)
public CommonResult handleException(Exception e) {
LOG.error(e.getMessage(), e);
return CommonResult.error(HttpStatus.INTERNAL_SERVER_ERROR.value(), "操作失败!,系统异常," + ExceptionUtils.getRootCauseMessage(e));
}
/**
* 处理所有业务异常
*/
@ExceptionHandler(BusinessRuntimeException.class)
public ResponseEntity handleOpdRuntimeException(BusinessRuntimeException e) {
// 不打印异常堆栈信息
LOG.error(e.getMsg());
if("409".equals(e.getCode())){
return ResponseEntity.status(HttpStatus.CONFLICT.value()).body("不能重复建立连接!");
}else{
throw e;
}
}
}
二、ResponseEntity更改HTTP Status Code
/**
* 处理所有业务异常
*/
@ExceptionHandler(BusinessRuntimeException.class)
public ResponseEntity handleOpdRuntimeException(BusinessRuntimeException e) {
// 不打印异常堆栈信息
LOG.error(e.getMsg());
if("409".equals(e.getCode())){
return ResponseEntity.status(HttpStatus.CONFLICT.value()).body("不能重复建立连接!");
}else{
throw e;
}
}
HTTP Status Code
分类 | 分类描述 |
---|
1** | 信息,服务器收到请求,需要请求者继续执行操作 |
2** | 成功,操作被成功接收并处理 |
3** | 重定向,需要进一步的操作以完成请求 |
4** | 客户端错误,请求包含语法错误或无法完成请求 |
5** | 服务器错误,服务器在处理请求的过程中发生了错误 |
常用的几种状态码
状态码 | 英文名 | 中文描述 |
---|
200 | OK | 请求成功。一般用于GET与POST请求 |
201 | Created | 已创建。成功请求并创建了新的资源 |
202 | Accepted | 已接受。已经接受请求,但未处理完成 |
400 | Bad Request | 客户端错误,请求包含语法错误或无法完成请求 |
401 | Unauthorized | 请求要求用户的身份认证 |
403 | Forbidden | 服务器理解请求客户端的请求,但是拒绝执行此请求 |
404 | Not Found | 服务器无法根据客户端的请求找到资源(网页) |
500 | Internal Server Error | 服务器内部错误,无法完成请求 |
501 | Not Implemented | 服务器不支持请求的功能,无法完成请求 |
503 | Service Unavailable | 由于超载或系统维护,服务器暂时的无法处理客户端的请求 |
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)