0
点赞
收藏
分享

微信扫一扫

SpringMVC ---- 异常

小北的爹 2022-03-30 阅读 19
springjava

文章目录

异常处理

在这里插入图片描述

异常处理器(实现接口的方式:一般不用)【了解】

在这里插入图片描述

package com.itheima.exception;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

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

@Component
public class ExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Object handler,
                                         Exception ex) {
        System.out.println("my exception is running ...."+ex);
        ModelAndView modelAndView = new ModelAndView();
        if( ex instanceof NullPointerException){
            modelAndView.addObject("msg","空指针异常");
        }else if ( ex instanceof  ArithmeticException){
            modelAndView.addObject("msg","算数运算异常");
        }else{
            modelAndView.addObject("msg","未知的异常");
        }
        modelAndView.setViewName("error.jsp");
        return modelAndView;
    }
}

error.jsp

<%--异常消息展示页面--%>
<%@page pageEncoding="UTF-8" language="java" contentType="text/html;UTF-8" %>

${msg}

注解实现异常处理

package com.itheima.exception;

import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Component
//使用注解开发异常处理器
//声明该类是一个Controller的通知类,声明后该类就会被加载成异常处理器
//可以在controller的前后做功能增强
@ControllerAdvice
public class ExceptionAdvice {

    //类中定义的方法携带@ExceptionHandler注解的会被作为异常处理器,后面添加实际处理的异常类型
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public String doNullException(Exception ex){
        return "空指针异常";
    }

    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public String doArithmeticException(Exception ex){
        return "ArithmeticException";
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String doException(Exception ex){
        return "all";
    }

}

项目异常处理方案【理解】

在这里插入图片描述
在这里插入图片描述

自定义异常

业务异常(用户) BusinessException

package com.itheima.exception;
//自定义异常继承RuntimeException,覆盖父类所有的构造方法
public class BusinessException extends RuntimeException {
    public BusinessException() {
    }

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(String message, Throwable cause) {
        super(message, cause);
    }

    public BusinessException(Throwable cause) {
        super(cause);
    }

    public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

系统异常: SystemException

package com.itheima.exception;
//自定义异常继承RuntimeException,覆盖父类所有的构造方法
public class SystemException extends RuntimeException {
    public SystemException() {
    }

    public SystemException(String message) {
        super(message);
    }

    public SystemException(String message, Throwable cause) {
        super(message, cause);
    }

    public SystemException(Throwable cause) {
        super(cause);
    }

    public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

其他异常: DevelopException

package com.itheima.exception;
//自定义异常继承RuntimeException,覆盖父类所有的构造方法
public class DevelopException extends RuntimeException {
    public DevelopException() {
    }

    public DevelopException(String message) {
        super(message);
    }

    public DevelopException(String message, Throwable cause) {
        super(message, cause);
    }

    public DevelopException(Throwable cause) {
        super(cause);
    }

    public DevelopException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

将异常包装为自定义异常

    public void save(){
        //业务层中如果出现了异常,就对出现异常的代码进行try...catch...处理
        //在catch中将出现的异常包装成自定义异常,同时务必将当前异常对象传入自定义异常,避免真正的异常信息消失
        try {
            throw new SQLException();
        } catch (SQLException e) {
            throw new SystemException("数据库连接超时!",e);
        }
    }

统一处理异常

package com.itheima.exception;

import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@Component
@ControllerAdvice
public class ProjectExceptionAdvice {

    @ExceptionHandler(BusinessException.class)
    @ResponseBody()
    public String doBusinessException(Exception ex, Model m){
        //使用参数Model将要保存的数据传递到页面上,功能等同于ModelAndView
        //业务异常出现的消息要发送给用户查看
//        m.addAttribute("msg",ex.getMessage());
        return ex.getMessage();
    }

    @ExceptionHandler(value = {SystemException.class})
    @ResponseBody
    public String doSystemException(Exception ex, Model m){
        //系统异常出现的消息不要发送给用户查看,发送统一的信息给用户看
//        m.addAttribute("msg","服务器出现问题,请联系管理员!");
        //实际的问题现象应该传递给redis服务器,运维人员通过后台系统查看
        //实际的问题显现更应该传递给redis服务器,运维人员通过后台系统查看
        return "服务器出现问题,请联系管理员!";
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String doException(Exception ex, Model m){
//        m.addAttribute("msg",ex.getMessage());
        //将ex对象保存起来
        return ex.getMessage();
    }

}

异常中文乱码问题

异常处理器中的中文处理

推荐博客
https://www.jianshu.com/p/b87ffc816903
https://blog.csdn.net/Numb_ZL/article/details/122273878

比较推荐的方法是

  <mvc:annotation-driven>
        <!--指定StringHttpMessageConverter的字符集-->
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/plain;charset=utf-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

controller中的中文处理

https://www.cnblogs.com/userzf/p/13824972.html

@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")  
@ResponseBody  
public Pet getPet(@PathVariable String petId, Model model) {     
    // implementation omitted  
}  


//由于添加了ResponseBody所以可以省略调 produces="application/json"
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET)  
@ResponseBody  
public Pet getPet(@PathVariable String petId, Model model) {     
    // implementation omitted  
}  

produces:添加处理后的编码
consumes:添加请求类型限制

    @PostMapping(value="/out",produces="application/json;charset=UTF-8,text/html;charset=UTF-8",consumes="application/json")
    @ResponseBody
    public String outInfo(@RequestBody User user) {

        return "我是中文";
    }
举报

相关推荐

0 条评论