SpringMVC异常处理---@ExceptionHandler

1. @ExceptionHandler

告诉springmvc这个方法专门处理这个类发生的异常
1.给方法上随便写一个Exception,用来接收发生的异常
2.要携带异常信息不能给参数位置写model
3.返回modelandview
4.如果有多个@ExceptionHandler都能处理这个异常,精确 优先
5.全局异常处理与本类同时存在,本类优先

@Controller
public class ExceptionHandler {
	
	@RequestMapping("/exc01")
	public void test() {
		int i=10/0;
		System.out.println(i);
	}
	
	@org.springframework.web.bind.annotation.ExceptionHandler(value= {ArithmeticException.class})
	public ModelAndView handler(Exception exception) {
		ModelAndView view = new ModelAndView("error");
		view.addObject("ex", exception);
		return view;
			
	}
<body>
<h1>发生错误了</h1>
${ex }

</body>

在这里插入图片描述

2.集中处理所有异常

1.集中处理所有异常的类加入到IOC容器中
2.。@ControllerAdvice专门处理异常的类

3、自定义异常

(前提没有其他异常处理方法)
继承RuntimeException

package com.atguigu.controller;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(reason="用户拒绝登录", value=HttpStatus.NOT_EXTENDED)
public class UserNameNotFoundException extends RuntimeException{

	private static final long serialVersionUID = 1L;
	

}

请求处理

	@RequestMapping("/exc02")
	public String test2(@RequestParam("username")String username) {
		
		if (!"admin".equals(username)) {
			System.out.println("登录失败");
			throw new UserNameNotFoundException();		
		}
		System.out.println("登陆成功");
		return "/list";
		
	}
	
	

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值