All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.feingto.cloud.config.web.ExceptionResolverUtil Maven / Gradle / Ivy

The newest version!
package com.feingto.cloud.config.web;

import com.feingto.cloud.kit.HttpKit;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 异常解析工具
 *
 * @author longfei
 */
public class ExceptionResolverUtil {
    public static final String LINE_SEPARATOR = "
"; public static ModelAndView handleException(HttpServletRequest request, int status, String error) { if (HttpKit.isAjaxWithRequest(request)) { return renderJsonView(status, error); } Map map = new HashMap<>(); map.put("code", status); map.put("error", error); return new ModelAndView("error/500", map, HttpStatus.valueOf(status)); } public static ModelAndView renderJsonView(int status, String message) { ModelAndView mv = new ModelAndView(new MappingJackson2JsonView()) .addObject("success", false) .addObject("code", status) .addObject("message", message); return Optional.ofNullable(HttpStatus.resolve(status)) .map(httpStatus -> { mv.setStatus(httpStatus); mv.addObject("error", httpStatus.getReasonPhrase()); return mv; }) .orElseGet(() -> { String code = String.valueOf(status); HttpStatus s = HttpStatus.valueOf(code.length() > 3 ? Integer.parseInt(code.substring(0, 3)) : status); mv.setStatus(s); mv.addObject("error", s.getReasonPhrase()); return mv; }); } public static String trace(Throwable t) { return t.getCause() == null ? t.getMessage() : trace(t.getCause()); } public static String resolverException(Exception ex, String message) { return StringUtils.hasText(ex.getMessage()) ? trace(ex) : message; } public static String resolverBindException(BindingResult result) { List errorList = result.getFieldErrors(); StringBuilder sb = new StringBuilder(); for (FieldError fieldError : errorList) { sb.append("[") .append(fieldError.getField()) .append("]验证失败: ") .append(fieldError.getDefaultMessage()) .append(LINE_SEPARATOR); } sb.deleteCharAt(sb.length() - LINE_SEPARATOR.length()); return sb.toString(); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy