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