全局捕获异常

项目经常会遇到一些常见的异常,如:404  ,500,这中错误给客户看到肯定是体验不好的

解决方法:

1 .添加try catch

2编写全局异常处理

本文主要将第二种

 

首先看下目录结构:

所用到的注解:

@ExceptionHandler 指定捕获的异常类
@ControllerAdvice 扫包
@ResponseBody 不加没法返回的

创建全局错误处理类

这里提供两,一个直接返回json,一个是跳转页面的

package com.cn.demo.error;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice(basePackages = "com.cn.demo")
public class error {
    //非跳转页面
//    @ExceptionHandler(RuntimeException.class)
//    @ResponseBody
//    public Map<String,Object> errorResult(){
//        Map<String,Object> map = new HashMap<String,Object>();
//        map.put("errorCode",500);
//        map.put("errorMassage","系统错误");
//        return map;
//    }
    //跳转错误页面
    //指定捕获的异常类型
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public ModelAndView errorResult(){
        ModelAndView view =new ModelAndView();
        view.setViewName("error");
        return view;
    }

}

java类

 

package com.cn.demo.controller;

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


@RestController
public class getUser {
    @RequestMapping("/User")
    public String getUser(int i){
        int j=1/i;
         return "success";
    }

}

测试结果

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值