ExceptionHandler 异常公共处理

本文介绍了两种在Spring框架下处理异常的方法:一是通过继承AbstractHandlerExceptionResolver类实现全局异常处理;二是使用@ControllerAdvice注解配合@ExceptionHandler注解进行异常处理。文中详细展示了如何针对不同类型的异常进行日志记录及响应。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

异常的公共处理很多种,采用注解的方式,拦截器的方式等都可以,我采用的是继承 AbstractHandlerExceptionResolver 来实现,

上代码

package com.yun.util;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import com.alibaba.druid.support.json.JSONUtils;

public class ExceptionHandler extends AbstractHandlerExceptionResolver {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request,
            HttpServletResponse response, Object handler, Exception ex) {
        
        // SQLException 数据库异常
        if (ex instanceof SQLException) {
            SQLException e = (SQLException) ex;
            LOGGER.error("数据库异常:{}",e.getMessage());
        }
        // RuntimeException>NullPointerException,IllegalArgumentException...
        if (ex instanceof RuntimeException) {
            RuntimeException e = (RuntimeException) ex;
            LOGGER.error("运行时异常:{}",e.getMessage());
        }
        
        // IOException
        if (ex instanceof IOException) {
            IOException e = (IOException) ex;
            LOGGER.error("IO异常:{}",e.getMessage());
        }
        
        // TimeoutException
        if (ex instanceof TimeoutException) {
            TimeoutException e = (TimeoutException) ex;
            LOGGER.error("超时:{}",e.getMessage());
        }
        
        if(handler instanceof HandlerMethod){
            
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Class returnType = handlerMethod.getMethod().getReturnType();
            try {
                if(returnType == String.class||returnType==void.class){
                    String rsp = JSONUtils.toJSONString(ex);
                    response.setContentType("application/json;charset=UTF-8");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(rsp);
                    new ModelAndView();
                }
                if(returnType == ModelAndView.class){
                    Map<String, Object> model = new HashMap<String, Object>();  
                    model.put("ex", ex);  
                    return new ModelAndView("error/error", model);  
                }
            } catch (Exception e) {
                LOGGER.error("异常:{}", e.getMessage());
            }
            
        }
        
        return new ModelAndView();
        
    }

}

 

接下来只需要注册到spring中就ok了。

<!-- 异常处理 -->
    <bean class="com.midea.jr.efc.eac.core.web.ExceptionHandler"></bean>

 二: 另一种方式  注解 ControllerAdvice

package com.yun.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class CommonExceptiomHandler {
    
    private Logger logger =  LoggerFactory.getLogger(this.getClass());
    
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public String illegalArgumentException(IllegalArgumentException e) {
        logger.error(e.getMessage());
        return new String("param error");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public String MissingServletRequestParameterException(MissingServletRequestParameterException e) {
        logger.error(e.getMessage());
        return new String("missing servlet request");
    }

    @ExceptionHandler(TypeMismatchException.class)
    @ResponseBody
    public String typeMismatchException(TypeMismatchException e) {
        logger.error(e.getMessage());
        return new String("type mismatch error");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public String httpRequestMethodNotSupportedException(Exception e) {
        logger.error(e.getMessage());
        return new String("http request method not supported");
    }
    
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String defaultException(Exception e) {
        logger.error(e.getMessage());
        return new String("system error");
    }

}

 

转载于:https://www.cnblogs.com/yun965861480/p/6613244.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值