SpringBoot中异常处理

本文先介绍默认的异常处理类,然后介绍自定义的异常处理

默认的异常处理类BasicErrorController

默认的基础处理类BasicErrorController处理异常的路径是/error,对于请求头中带有text/html的请求返回的是页面,如果在
classpath/error下定义404.html或者对应的状态码的html页面的话就会返回对应的页面否则的话就是默认的页面.对于请求头中没有text/html的返回json数据.默认的json数据中会包含异常的message或者是校验注解中的message(要看Controller方法参数中有没有BindingResult对象,BindingResult对象一定要紧跟在进行校验的参数后面.没有这个对象的话,参数校验错误的时候请求不会进入到请求体中)

package org.springframework.boot.autoconfigure.web;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.ErrorProperties.IncludeStacktrace;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
  private final ErrorProperties errorProperties;

  public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
    this(errorAttributes, errorProperties, Collections.emptyList());
  }

  public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
    super(errorAttributes, errorViewResolvers);
    Assert.notNull(errorProperties, "ErrorProperties must not be null");
    this.errorProperties = errorProperties;
  }

  public String getErrorPath() {
    return this.errorProperties.getPath();
  }

  @RequestMapping(
    produces = {"text/html"}
  )
  public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    HttpStatus status = this.getStatus(request);
    Map<String, Object> model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
    response.setStatus(status.value());
    ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
    return modelAndView == null ? new ModelAndView("error", model) : modelAndView;
  }

  @RequestMapping
  @ResponseBody
  public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
    Map<String, Object> body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
    HttpStatus status = this.getStatus(request);
    return new ResponseEntity(body, status);
  }

  protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
    IncludeStacktrace include = this.getErrorProperties().getIncludeStacktrace();
    if (include == IncludeStacktrace.ALWAYS) {
      return true;
    } else {
      return include == IncludeStacktrace.ON_TRACE_PARAM ? this.getTraceParameter(request) : false;
    }
  }

  protected ErrorProperties getErrorProperties() {
    return this.errorProperties;
  }
}

自定义返回的json数据,进行统一的异常处理

自定义异常

在定义的异常之中传入详细的异常信息

package com.micro.fast.security.demo.exception;

/**
 * 自定义异常,传入详细的异常信息
 */
public class UserNotExistsException extends RuntimeException {

  private String id;
  public UserNotExistsException(String id){
    super("user not exist");
    this.id=id;
  }

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }
}

定义异常统一处理类,app访问会返回这里的json信息

import com.micro.fast.security.demo.exception.UserNotExistsException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

//异常处理类
@RestControllerAdvice
public class ControllerExceptionHandler{

  //处理UserNotExists异常,当app调用的时候返回这里的信息
  @ExceptionHandler(UserNotExistsException.class)
  @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)//定义返回的http状态码
  public Map<String,Object> handlerUserNotExitsHandler(UserNotExistsException ex){//将发生的对象传入这个函数之中
    return null;
  }
}

发生异常时在Controller方法中抛出异常即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值