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 各种方式的校验

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值