SpringBoot official document example: (55) Controller’s local abnormal processing @ExceptionHandler Note Amadeus

2023-02-20  

You can use @Exceptionhandler to perform local abnormal treatment of controller.

package com.example.controller;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;


import javax.servlet.http.HttpServletRequest;

@RestController
public class ArithmeticController {
    @RequestMapping("/divideTest/{a}/{b}")
    public int divideTest(@PathVariable("a") int a,@PathVariable("b") int b){
        int result=a/b;
        int t=1/0;

        return result;
    }

    @ExceptionHandler(ArithmeticException.class)
    int  handleCustomException(HttpServletRequest request, ArithmeticException ex) {
        //request.setAttribute(ErrorAttributes.ERROR_ATTRIBUTE, ex);
        return -1;
    }

}

Use postman to perform interface tests:
在这里插入图片描述
can see that when zero abnormal occurrence occurs, the return value of the abnormal processing method of the @ExceptionHandler annotation mark is returned

source

Random Posts

IDA’s DEF.H file

javamail implements automatic send emails

PTA Zhejiang University Edition “C Language Program Design (3rd Edition)” Title Collection 2-5 Seeking N itself n and

Draw a histogram+column -like chart zhaohui

java object to JOSN format string, value is set to NULL to be filtered