spring boot——请求与参数校验——重要概念——异常处理——@ControllerAdvice注解——清华

 

 

 

 

 

 

 

PS,访问资源,引入如下:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

 

 

 

 

 

 

 

 

 

自定义注解:

package org.example.Exception;

public class MyException extends Exception
{

    private static final long serialVersionUID = 1L;


    public MyException()
    {

        super();
    }


    public MyException(String message)
    {

        super(message);
    }
}

 

 

 

 

 

 

 

设置全局异常类:

package org.example.controller.GlobalExceptionHandler;

import org.example.Exception.MyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.sql.SQLException;

@ControllerAdvice
public class GlobalExceptionHandlerController
{
    @ExceptionHandler(value=Exception.class)
    public String handlerException(Exception e)
    {
        //数据库异常
        if (e instanceof SQLException)
        {

            System.out.println(e.getMessage());

            return "sqlError";
        }
        else if (e instanceof MyException)   //自定义异常
        {

            return "myError";
        }
        else          //未知异常
        {
            return "noError";
        }
    }
}

 

 

 

 

 

 

 

设置controller,用于访问并引发异常:

package org.example.controller.GlobalExceptionHandler;

import org.example.Exception.MyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.sql.SQLException;

@Controller
public class HandleExceptionController
{
    @RequestMapping("/f123")
    public String index()
    {

        return "index";
    }

    @RequestMapping("/db")
    public void db() throws SQLException
    {

        throw new SQLException("数据库异常");
    }

    @RequestMapping("/my")
    public void my() throws MyException
    {

        throw new MyException("自定义异常");
    }

    @RequestMapping("/no")
    public void no() throws Exception
    {

        throw new Exception("未知异常");
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2023-01-21 23:44  小白龙白龙马  阅读(64)  评论(0)    收藏  举报