sprig中基于注解的异常处理

本文简述在spring中使用注解对Controller中抛出的异常进行单独处理或统一处理。


1、单独处理当前controller中的异常

主要的controller代码如下,代码中访问hello时会直接抛出DuplicateElementException异常从而执行exception中的返回。使用浏览器可以看到返回"Hello,world"的字样。

package cn.hifei.spring.demo.web.controller;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.mchange.util.DuplicateElementException;

@RestController
public class TestController {
	
	@ExceptionHandler(DuplicateElementException.class)
	public String exeption() {
		return "Hello,world";
	}

	@RequestMapping(value="hello",method=RequestMethod.GET)
	public String test() throws Exception {
		throw new DuplicateElementException();
	}
}

2、统一处理异常

当需要对多个controller中抛出的异常进行统一处理时,可以使用@RestControllerAdvice或@ControllerAdvice标注一个异常处理类,由于@RestControllerAdvice(在基于spring的restful的controller中使用)或@ControllerAdvice(在普通的controller中使用)中已经使用了@Component注解,因此可以自动被扫描到。如下

package cn.hifei.spring.demo.web.exception;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class AppWideExceptionHandler {
	
	@ExceptionHandler(IllegalArgumentException.class)
	public String exceptionHandler() {
		return "Oh,No!";
	}
}

测试的controller代码如下:

当访问hello2时会直接抛出IllegalArgumentException异常从而跳转到AppWideExceptionHandler类中的exceptionHandler方法中执行,浏览器上可以看到"Oh,No!"的字样。

package cn.hifei.spring.demo.web.controller;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.mchange.util.DuplicateElementException;

@RestController
public class TestController {
	
	@ExceptionHandler(DuplicateElementException.class)
	public String exeption() {
		return "Hello,world";
	}

	@RequestMapping(value="hello2",method=RequestMethod.GET)
	public String test2() throws IllegalArgumentException{
		throw new IllegalArgumentException();
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值