SpringBoot2.X之旅,@ExceptionHandler、@ControllerAdvice异常统一处理(Web Project)

一、idea新建web项目

pom.xml如下:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
         
    
    com.cobra
    exceptiondemo
    0.0.1-SNAPSHOT
    exceptiondemo
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

目录结构:

SpringBoot2.X之旅,@ExceptionHandler、@ControllerAdvice异常统一处理(Web Project)_第1张图片

二、coding:

1、在DemoController,写一个异常:

package com.cobra.exceptiondemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Baron
 * @Description:
 * @Date: Created in 2019/4/16 10:25
 */
@RestController
@Slf4j
public class DemoController {

    @GetMapping("/demo")
    public String demo() {

        int[] arrays = {1, 23, 6, 7};
        for (int i = 0; i <= arrays.length ; i++) {
            log.info("int[{}]={}",i,arrays[i]);
        }
        return "this is an demo test";
    }

}

2、在DemoExceptionHandler,捕获异常,返回自定义的信息:

package com.cobra.exceptiondemo.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Author: Baron
 * @Description:
 * @Date: Created in 2019/4/16 10:26
 */
@ControllerAdvice
@Slf4j
public class DemoExceptionHandler {

    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    @ResponseBody
    public String handlerArrayIndexOutOfBoundsException(ArrayIndexOutOfBoundsException e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return "数组下标越界";
    }

}

三、测试:

SpringBoot2.X之旅,@ExceptionHandler、@ControllerAdvice异常统一处理(Web Project)_第2张图片

SpringBoot2.X之旅,@ExceptionHandler、@ControllerAdvice异常统一处理(Web Project)_第3张图片

你可能感兴趣的:(springboot)