一、@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**服务器错误,服务器在处理请求的过程中发生了错误

常用的几种状态码

状态码英文名中文描述
200OK请求成功。一般用于GET与POST请求
201Created已创建。成功请求并创建了新的资源
202Accepted已接受。已经接受请求,但未处理完成
400Bad Request客户端错误,请求包含语法错误或无法完成请求
401Unauthorized请求要求用户的身份认证
403Forbidden服务器理解请求客户端的请求,但是拒绝执行此请求
404Not Found服务器无法根据客户端的请求找到资源(网页)
500Internal Server Error服务器内部错误,无法完成请求
501Not Implemented服务器不支持请求的功能,无法完成请求
503Service Unavailable由于超载或系统维护,服务器暂时的无法处理客户端的请求

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐