springboot 全局异常拦截器

springboot异常拦截器

mvc异常拦截器

package com.eaos.util.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

@Configuration
public class GolbalException implements HandlerExceptionResolver {

	/**
	 * 	异常
	 * @return
	 */
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("errorInfo", "全局异常处理" + ex.getMessage());
		System.out.println(ex.getMessage());
		System.out.print("异常栈:");
		//ex.getStackTrace();
		return mv;
	}

}

前后端分离拦截器

package com.eaos.util.exception;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

	 private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	/*这个类可以进行自定义返回类型*/
	@ExceptionHandler(value = Exception.class)
	public void allExceptionHandel(HttpServletRequest request,HttpServletResponse response, Exception e) throws IOException {
		logger.error(e.getMessage(), e);
		System.out.println("系统异常:"+e.getMessage());
		// 返回结果
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		Map<String, Object> map = new HashMap<>();
		map.put("code", "505");
		map.put("msg", "系统异常");
		writer.write(JSON.toJSONString(map));
		writer.flush();
		writer.close();
	}
	/*
	@ExceptionHandler(value = Exception.class)
	public Map<String, Object> allExceptionHandel(HttpServletRequest request,HttpServletResponse response, Exception e) throws IOException {
		logger.error(e.getMessage(), e);
		System.out.println("系统异常:"+e.getMessage());
	Map<String, Object> map = new HashMap<>();
		map.put("code", "505");
		map.put("msg", "系统异常");
		return map;
	}
	*/
}

全局异常处理类

package com.videos.video.common.exception;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.videos.video.common.result.Result;
import com.videos.video.common.result.ResultEnum;
import com.videos.video.common.result.ResultUtil;
import com.videos.video.common.util.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.security.auth.login.LoginException;
import java.util.List;

/**
 * 描述:全局异常处理类只需要在类上标注@RestControllerAdvice,并在处理相应异常的方法上使用@ExceptionHandler注解,写明处理哪个异常即可。
 *
 * @author panxg
 * @date 2020年12月05日 23:29
 */
// 统一的异常类进行处理(把默认的异常返回信息改成自定义的异常返回信息)
// 当GlobalContrller抛出HospitalException异常时,将自动找到此类中对应的方法执行,并返回json数据给前台
@Slf4j
@RestControllerAdvice
public class ExceptionConfig {



    /**
     * 忽略参数异常处理器
     *
     * @param e 忽略参数异常
     * @return ResponseResult
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<String> parameterMissingExceptionHandler(MissingServletRequestParameterException e) {
        log.error("忽略参数异常:{},{}", e.getMessage(),e);
        //return ResultUtil.failure("-1","请求参数 " + e.getParameterName() + " 不能为空");
        return ResultUtil.failure(ResultEnum.PARAM_ERROR,e.getMessage());
    }


    /**
     * 缺少请求体异常处理器
     *
     * @param e 缺少请求体异常
     * @return ResponseResult
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<String> parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
        log.error("缺少请求体异常:{},{}", e.getMessage(),e);
        //return ResultUtil.failure("-1","参数体不能为空");
        return ResultUtil.failure(ResultEnum.PARAM_ERROR,e.getMessage());
    }

    /**
     * 参数效验异常处理器
     *
     * @param e 参数验证异常
     * @return ResponseInfo
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> parameterExceptionHandler(MethodArgumentNotValidException e) {
        log.error("参数效验异常处理器:{},{}", e.getMessage(),e);
        // 获取异常信息
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return ResultUtil.failureMsg(fieldError.getDefaultMessage());
            }
        }
        return ResultUtil.failure(ResultEnum.PARAM_ERROR,e.getMessage());
    }

    /**
     * 自定义参数错误异常处理器
     *
     * @param e 自定义参数
     * @return ResponseInfo
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({BusinessException.class})
    public Result<String> paramExceptionHandler(BusinessException e) {
        log.error("自定义异常:{},{}", e.getMessage(),e);
        // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
        if (!StringUtils.isBlank(e.getMessage())) {
            return ResultUtil.failure(ResultEnum.PARAM_ERROR.setMsg(e.getMessage()));
        }
        return ResultUtil.failure(ResultEnum.PARAM_ERROR);
    }

    /**
     * 其他异常
     *
     * @param e
     * @return
     */
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler({Exception.class})
    public Result<String> otherExceptionHandler(Exception e) {
        log.error("其他异常:{},{}", e.getMessage(),e);
        // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
        if (!StringUtils.isEmpty(e.getMessage())) {
            return ResultUtil.failure(ResultEnum.SERVICE_FAILURE.setMsg(e.getMessage()));
        }
        return ResultUtil.failure(ResultEnum.SERVICE_FAILURE);
    }

    /**
     * @param @return @exception
     * @Description //异常处理器,处理WxPayException异常
     * @Author panxg
     * @Date 2020/12/5 23:31
     **/
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = WxPayException.class)
    public Result<String> hanlerException(WxPayException wxPayException) {
        log.error("微信异常:{},{}", wxPayException.getMessage(),wxPayException);
        return ResultUtil.failure(ResultEnum.WX_PAY_EXCEPTION.setMsg(wxPayException.getReturnMsg()));
    }


    /**
     * @param @return @exception
     * @Description //异常处理器,处理loginException异常
     * @Author panxg
     * @Date 2020/12/5 23:31
     **/
    @ExceptionHandler(value = LoginException.class)
    public Result<String> loginException(LoginException loginException) {
        log.error("登录异常:{},{}", loginException.getMessage(),loginException);
        return ResultUtil.failure(ResultEnum.LOGIN_FAILURE_200402.setMsg(loginException.getMessage()));
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值