springMVC-异常统一处理

1 将异常映射为HTTP状态码

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

/**
 * @Author:musi
 * @Date:2019/9/4
 * @Description:
 */
@ResponseStatus(value = HttpStatus.NOT_FOUND,reason = "spittle not found")
public class SpittleNotFoundException extends RuntimeException {

}

在使用@ResponseStatus注解之后,如果控制器方法抛出SpittleNotFoundException异常的话,响应将会具有404状态码,这是因为Spittle Not Found

2 统一处理单个controller中的异常

import com.musi.exception.DuplicateSpittleException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @Author:musi
 * @Date:2019/8/25
 * @Description:
 */
@Controller
public class HomeController {

    @RequestMapping(value="/",method = RequestMethod.GET)
    public String home(){

        boolean isThrowException = true;
        if(isThrowException){
            throw new DuplicateSpittleException();
        }
        return "home";
    }

    @RequestMapping(value="/test",method = RequestMethod.GET)
    public String test(){

        boolean isThrowException = true;
        if(isThrowException){
            throw new DuplicateSpittleException();
        }
        return "test";
    }

    @ExceptionHandler(DuplicateSpittleException.class)
    public String handleDuplicateSpittle(){
        return "error/duplicate";
    }

}

在使用@ExceptionHandler注解之后,如果当前controller方法抛出DuplicateSpittleException异常的话,程序都会进入handleDuplicateSpittle方法,最终返回到error/duplicate页面

3 统一处理所有controller中的异常

import com.musi.exception.DuplicateSpittleException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/**
 * @Author:musi
 * @Date:2019/9/4
 * @Description:
 */
@ControllerAdvice
public class AppWideExceptionHandler {

    @ExceptionHandler(DuplicateSpittleException.class)
    public String handleDuplicateSpittle(){
        return "error/duplicate";
    }

}

在使用@ControllerAdvice和@ExceptionHandler注解之后,所有的controller带有RequestMapping的方法如果抛出DuplicateSpittleException异常的话,程序都会进入handleDuplicateSpittle方法,最终返回到error/duplicate页面

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值