您的位置:首页 > 编程语言 > Java开发

SpringMVC处理异常

2017-02-07 16:08 211 查看

SpringMVC处理异常

@(SpringMVC)[springmvc, 异常]

SpringMVC处理异常
SpringMVC单异常处理
SpitterController2

SpittleNotFoundException

MyError

springMvc架构级别异常处理
案例
自定义异常类

自定义全局异常处理器

错误页面errorjsp

在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


前端控制器交由异常处理器进行异常处理,如下图:



案例

自定义异常类

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
,出现“用户不存在!”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息