SpringMVC处理异常

SpringMVC处理异常

@(SpringMVC)[springmvc, 异常]

SpringMVC单异常处理

SpitterController2

package spittr.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import spittr.Spittle;
import spittr.data.SpitterRepository;

// 使用RestController,相当于在每个方法上加上了@ResponseBody
@RestController
@RequestMapping("/spitter2")
public class SpitterController2 {

    private SpitterRepository spitterRepository;

    @Autowired
    public SpitterController2(SpitterRepository spitterRepository) {
        this.spitterRepository = spitterRepository;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public Spittle spittleById(@PathVariable long id) {
        Spittle spittle = spitterRepository.findOne(id);
        if (spittle == null) {
            throw new SpittleNotFoundException(id);
        }
        return spittle;
    }

    @ExceptionHandler(SpittleNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public MyError spittleNotFound(SpittleNotFoundException e) {
        long spittleId = e.getSpittleId();
        return new MyError(4, "Spittle[" + spittleId + "] not found");
    }

}

SpittleNotFoundException

package spittr.web;

/**
 * Created by Switch on 2017/1/14.
 */
public class SpittleNotFoundException extends RuntimeException {
    private long spittleId;

    public SpittleNotFoundException(long spittleId) {
        this.spittleId = spittleId;
    }

    public long getSpittleId() {
        return spittleId;
    }
}

MyError

package spittr.web;

/**
 * Created by Switch on 2017/1/14.
 */
public class MyError {
    private int code;
    private String message;

    public MyError(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

springMvc架构级别异常处理

系统中异常包括两类:预期异常和运行时异常RuntimeException,前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试通过手段减少运行时异常的发生。
系统的dao、service、controller 出现都通过throws Exception 向上抛出,最后由springmvc
前端控制器交由异常处理器进行异常处理,如下图:
SpringMVC异常处理

案例

自定义异常类
package com.pc.ssm.exception;

/**
 * 自定义异常
 * 
 * @author Switch
 * @data 2017年1月13日
 * @version V1.0
 */
public class CustomException extends Exception {
    private static final long serialVersionUID = -665787561868437767L;
    // 异常消息
    private String message;

    public CustomException() {

    }

    public CustomException(String message) {
        this.message = message;
    }


    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
自定义全局异常处理器
package com.pc.ssm.exception;

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

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

/**
 * 自定义全局异常处理器
 * 
 * @author Switch
 * @data 2017年1月13日
 * @version V1.0
 */
public class CustomGlobalExceptionResolver implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ex.printStackTrace();

        String msg = "";

        if (ex instanceof CustomException) {
            msg = ((CustomException) ex).getMessage();
        } else {
            msg = "系统繁忙,请稍后再试,或与管理员取得联系!";
        }
        ModelAndView modelAndView = new ModelAndView();
        // 添加错误信息
        modelAndView.addObject("error", msg);
        modelAndView.setViewName("error");
        return modelAndView;
    }

}
错误页面error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>系统通知</title>

    </head>
    <body> 
        <h2>${error}</h2>
    </body>
</html>
在SpringMVC配置文件中配置
    <!-- 配置异常处理器 -->
    <bean id="handlerExceptionResolver" class="com.pc.ssm.exception.CustomGlobalExceptionResolver"/>
创建异常
    @RequestMapping("/showEdit")
    public String showEdit(@RequestParam(value = "id") String id, Model model) throws Exception {
        User user = userService.findById(Integer.parseInt(id));
        // 创造个异常
        if(user == null) {
            throw new CustomException("用户不存在!");
        } else if(user.getId() == 1) {
            int i = 1 / 0;
        }
        model.addAttribute("user", user);
        return "edit";
    }
测试

访问:http://localhost:8080/SpringMVCAdvanced/user/showEdit.action?id=1,出现“系统繁忙,请稍后再试,或与管理员取得联系!”。
访问:http://localhost:8080/SpringMVCAdvanced/user/showEdit.action?id=2,正常访问。
访问:http://localhost:8080/SpringMVCAdvanced/user/showEdit.action?id=1000023,出现“用户不存在!”。

1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看REaDME.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值