SpringMVC之异常处理

SpringMVC之异常处理

异常分为编译时异常和运行时异常,编译时异常我们trycatch捕获,捕获后自行处理,而运行时异常是不可预期的,就需要规范编码来避免,在SpringMVC中,不管是编译异常还是运行时异常,都可以最终由SpringMVC提供的异常处理器进行统一管理,这样就可以避免随时随地捕获异常的繁琐性。

SpringMVC之异常处理_第1张图片

 

三种处理方式

1.简单异常处理器:使用Spring MVC内置的异常处理器处理:SimpleMappingExceptionResolver

@Component
public class MysimpleMappingExceton  {
    @Bean
    public SimpleMappingExceptionResolver simpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
        //默认错误
        simpleMappingExceptionResolver.setDefaultErrorView("default.html");
        Properties properties = new Properties();
        properties.setProperty("java.lang.ArithmeticExceotion","erro1.html");
        properties.setProperty("java.io.FileNotFoundException","erro2.html");
        simpleMappingExceptionResolver.setExceptionMappings(properties);
        return simpleMappingExceptionResolver;
    }
}

2.自定义异常处理器:实现HandlerExceptionResolver接口,自定义异常进行处理

@Component
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/default.html");
        return modelAndView;
    }
}

3.使用@ControllerAdvice@ExceptionHandler实现全局异常

@ControllerAdvice
public class GloExceotion {
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Result runtimeException(){
        Result result = new Result(200,"错误",new Object());
        return result;
    }
    @ExceptionHandler(FileNotFoundException.class)
    public ModelAndView fileNotException(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/erro2.html");
        return modelAndView;
    }
    @ExceptionHandler(Exception.class)
    public ModelAndView Exception(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/default.html");
        return modelAndView;
    }
}

例子

@RestController
public class ExceptionController {
    @RequestMapping("/e1")
    public String e1 (){
        int a=10/0;
        return "ruuning exception";
    }
    @RequestMapping("/e2")
    public String e2() throws FileNotFoundException {
        FileInputStream fileInputStream = new FileInputStream("file:/barch:/");
        return "ruuning exception";
    }
    @RequestMapping("/e3")
    public String e3()  {
        int [] array ={1,2};
        System.out.println(array[5]);
        return "ruuning exception";
    }
}

你可能感兴趣的:(SpringMVC,java,前端,tomcat)