springboot学习(六) springboot异常处理

Spring boot异常处理

springboot异常处理分为500错误和非500错误的处理。
非500错误,如404,401,403等使用自定义错误请求的方式,500的错误使用控制器拦截器的方式实现。

401等错误的处理。

  1. 定义一个配置类实现ErrorPageRegistar,添加各种类型错误页面的地址。 registry.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, “/404”));
    registry.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, “/403”));
package com.zqw.springboot.learn.boot.config;

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
    @Override
    public void registerErrorPages(ErrorPageRegistry registry) {
        registry.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/404"));
        registry.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/403"));
    }
}

2.自定义/401,/403错误请求,注意这样最好使用RequestMapping能够接收get,post,put等各种方式的请求,因为转发过来的请求可能是各种方式的。

package com.zqw.springboot.learn.boot.web;

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

@RestController
public class ErrorPageController {
    @RequestMapping("/403")
    public String to403(){
        return "403";
    }
    @RequestMapping("/404")
    public String to404(){
        return "404";
    }
}

500错误处理
500的错误指的是服务抛出的异常
1.定义一个RestControllerAdvice,这里可以拦截所有的异常请求,其实也可以定义多个方法,接收不同类型的异常,分别做处理。

package com.zqw.springboot.learn.boot.web;

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

@RestControllerAdvice
public class ExceptionAdivisor {
    @ExceptionHandler(value = Throwable.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String to500(Throwable throwable){
        return throwable.getMessage();
    }
}

github地址
springboot学习 上一篇 springboot添加拦截器
springboot学子 下一篇 springboot 各种方式的校验

猜你喜欢

转载自blog.csdn.net/u011943534/article/details/80806771