Springboot custom exception handling

Time:2022-5-5

Global exception handling

@ControllerAdvice
@RestController
public class GlobalExceptionInterceptor {

    //Exception exception
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e){
        e.printStackTrace();
        LogUtil.writeLog("error","log",e.getMessage()+e.getStackTrace());
        Result result = Result.errorResult();
        if (e.getClass().equals(HttpMediaTypeNotSupportedException.class)){
            result.setCode(-981);
            result. Setmsg ("request parameter format error");
        }else{
            result.setCode(-998);
            result. Setmsg ("system execution error");
        }

        return result;
    }

    //Runtime exception
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result exceptionHandler(RuntimeException e){
        e.printStackTrace();
        LogUtil.writeLog("error","log",e.getMessage()+e.getStackTrace());
        Result result = Result.errorResult();
        result.setCode(-997);
        result. Setmsg ("system operation error");
        return result;
    }

}

Global 404 interception

@Component
public class ResponseStatusInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(response.getStatus()==404){
            response.sendRedirect(request.getContextPath() + "/frame/error/404");
        }
        return true;
    }

}